facebookarchive/prepack

Verbose scope output for an IIFE

Open

#1,892 建立於 2018年5月8日

在 GitHub 查看
 (2 留言) (0 反應) (0 負責人)JavaScript (520 fork)batch import
enhancementhelp wantedserializer

倉庫指標

Star
 (14,268 star)
PR 合併指標
 (30 天內沒有已合併 PR)

描述

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?

貢獻者指南