我知道这听起来有点荒谬,但我正在寻找一种方法来将函数中的每个变量定义为 this
的属性。我正在寻找任何 hack,任何可能的方式来跟踪函数内的变量(即将它们添加到 this
对象),而不必实际在每个变量定义前加上这个。
。有办法吗?这可以通过 Proxy
实现吗?
function () {
// declare a variable
var hello = 'hi'
return this
}
let {hello} = function()
console.log(hello) // hi
例如这个有效:
function hi () { this.hello = true; return this }
hi.bind({})() // { hello: true }
我想要的是一种方法,让所有在 hi
中定义的变量在定义时添加到 this
对象中。
最佳答案
您正在寻找可以想象到的最糟糕的黑客攻击?当然,一切皆有可能:
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) }
});
}
代理声称包含所有可以在 with
范围内用作变量的名称。这基本上会导致所有未声明或 var
声明的变量的赋值在目标上创建属性(除非您使用 let
或 const
,它们将真正局限于 block 作用域)。
但是,对于变量查找,不是目标属性的所有内容都将在全局范围内解析(使用全局 eval
),因为当代理表示它可以传递所有变量时,无法保留原始范围。
关于javascript - 有什么方法可以将函数内的所有变量定义为 this 的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41049860/