Any way to define ALL variables within function as property of this?

孤人 提交于 2019-11-28 13:03:28

You are looking for the worst hack imaginable? Sure, everything is possible:

function example () {
  with(horrible(this)) {
    var hello = 'hi';
  }
}
var x = new example;
x.hello; // 'hi'


function horrible(target) {
  return new Proxy(target, {
    has() { return true; }, // contains all variables you could ever wish for!
    get(_, k) { return k in target ? target[k] : (1,eval)(k) }
  });
}

The proxy claims to contain all names that could ever be used as a variable in the with scope. This basically leads to all assignments of undeclared or var-declared variables create properties on the target (unless you use let or const, they'll be truly local to the block scope).
However, for variable lookup everything that is not a target property will be resolved in the global scope (using global eval) as the original scope cannot be retained when the proxy said it can deliver all variables.

You can, kind of. But it's a very very dirty hack which requires you to

  • Wrap the code inside a with statement, which has performance costs, is bad practice, and is not allowed in strict mode.
  • Use evil eval to get the values of the variables.
  • There can be false positives. Only var variables are detected, but not let or const ones.

function func() {
  // The proxy will detect the variables
  var vars = [];
  var proxy = new Proxy({}, {
    has(target, property) {
      vars.push(property);
    }
  });
  with(proxy) {
    // Place your code here
    var hello = 'hi';
  }
  // Assign the variables as properties
  for (var property of vars)
    this[property] = eval(property);
  return this;
}
let {hello} = func.call({});
console.log(hello) // hi
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!