facebookarchive/prepack

Verbose scope output for an IIFE

Open

#1.892 geöffnet am 8. Mai 2018

Auf GitHub ansehen
 (2 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)JavaScript (520 Forks)batch import
enhancementhelp wantedserializer

Repository-Metriken

Stars
 (14.268 Stars)
PR-Merge-Metriken
 (Keine gemergten PRs in 30 T)

Beschreibung

I noticed that just wrapping code into an IIFE changes makes the scope output verbose.

Before:

const x = 5;
const getDoubleOfX = () => 2 * x;
const setX = (newX) => { x = newX; }

global.getDoubleOfX = getDoubleOfX;
global.setX = setX;

Output:

let x;

(function () {
  var _0 = function () {
    return 2 * x;
  };

  var _1 = function (newX) {
    x = newX;
  };

  getDoubleOfX = _0;
  setX = _1;
  x = 5;
})();

After:

(function() {
  const x = 5;
  const getDoubleOfX = () => 2 * x;
  const setX = (newX) => { x = newX; }
  
  global.getDoubleOfX = getDoubleOfX;
  global.setX = setX;
})();

Output:

(function () {
  var __scope_0 = Array(1);

  var __scope_1 = function (__selector) {
    var __captured;

    switch (__selector) {
      case 0:
        __captured = [5];
        break;

      default:
        throw new Error("Unknown scope selector");
    }

    __scope_0[__selector] = __captured;
    return __captured;
  };

  var _0 = function () {
    var __captured__scope_2 = __scope_0[0] || __scope_1(0);

    return 2 * __captured__scope_2[0];
  };

  var _2 = function (newX) {
    var __captured__scope_2 = __scope_0[0] || __scope_1(0);

    __captured__scope_2[0] = newX;
  };

  getDoubleOfX = _0;
  setX = _2;
})();

I understand scope tracking makes sense when the closure is reused. But if it's just an IIFE, can we optimize and produce cleaner output?

Contributor Guide