在这个例子中:
var A = {test: 1, foo: function() { return this.test }}
为什么A.foo()返回1(至少在 node.js 中)?我以为this会绑定到外部调用者this,不是吗?
在这个例子中:
var A = {test: 1, foo: function() { return this.test }}
为什么A.foo()返回1(至少在 node.js 中)?我以为this会绑定到外部调用者this,不是吗?
当您调用时A.foo(),thiswithinfoo()设置为 object A,因为这就是您调用函数的原因。因此,this.test具有 的值1。
您可以使用或this更改引用的内容。.call().apply()
A.foo.call(newThisValue);
至于为什么……这给了你很大的灵活性。你可能有一个函数this来做某事,而 JavaScript 的构建方式允许你以object特定的方式将该函数应用于任何事情。这有点难以描述,但在继承等情况下确实派上用场。另见: http ://trephine.org/t/index.php?title=JavaScript_call_and_apply
在 Javascript中,每当您使用符号调用函数时,都会绑定到.obj.method()thisobj
您可以通过将调用拆分为两个单独的步骤来解决此问题:
var f = A.foo;
f(); // "this" will not be A in this case.
或者,滥用逗号运算符:
(17, x.f)()