【发布时间】:2016-12-08 22:21:02
【问题描述】:
我知道这可能听起来有点荒谬,但我正在寻找一种方法来将函数中的每个变量定义为this 的属性。我正在寻找任何 hack,任何可能的方式来跟踪函数中的变量(即将它们添加到 this 对象),而不必实际使用 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 对象的方法。
【问题讨论】:
-
this不是一个奇异的本性吗?对函数所有者的引用?任何变量都可以引用this,但它只引用一件事。可以通过.call或.apply更改。 -
你不能那样做。
标签: javascript this