有什么方法可以将函数中的所有变量定义为此属性?

Tho*_*ggi 1 javascript this

我知道这可能听起来有点荒谬,但我正在寻找一种方法来定义函数中的每个变量作为属性this.我正在寻找任何方法,以任何方式能够有一些方法来跟踪函数内的变量(即将它们添加到this对象),而不必实际为每个变量定义添加前缀this..有办法吗?这有可能Proxy吗?

function () {
  // declare a variable
  var hello = 'hi'
  return this
}

let {hello} = function()
console.log(hello) // hi
Run Code Online (Sandbox Code Playgroud)

例如,这有效:

function hi () { this.hello = true; return this }
hi.bind({})() // { hello: true }
Run Code Online (Sandbox Code Playgroud)

我想要的是一种方法,在定义所有变量时hi将其添加到this对象中.

Ber*_*rgi 8

您正在寻找可以想象的最糟糕的黑客?当然,一切皆有可能:

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) }
  });
}
Run Code Online (Sandbox Code Playgroud)

代理声称包含可以在with范围中用作变量的所有名称.这基本上导致所有未声明或已var声明变量的赋值在目标上创建属性(除非您使用letconst,它们将是块范围的真正本地).
但是,对于变量查找,所有不是目标属性的内容都将在全局范围内解析(使用全局eval),因为当代理表示它可以提供所有变量时,无法保留原始范围.