2013-03-20 64 views
0

在这个例子中:这是指什么?为什么?

var A = {test: 1, foo: function() { return this.test }} 

为什么A.foo()回报1(至少在node.js中)?我以为this将被绑定到外部呼叫者this,不是吗?

+0

为什么这指的是对象?我不完全明白为什么...... – Shouvik 2013-03-20 03:43:44

+0

为什么=理由,规则是什么。 – Mitar 2013-03-20 04:04:08

+0

[这是指在JavaScript私有方法中引用的]可能的重复(http://stackoverflow.com/questions/2259721/what-does-this-refer-to-in-a-javascript-private-method) – Shoe 2013-03-20 08:45:55

回答

5

当您拨打A.foo(),内foo()设置为对象A,因为这就是你所说的功能。因此,this.test的值为1

您可以使用.call() or .apply()更改引用this的内容。

A.foo.call(newThisValue); 

至于为什么......这给你很大的灵活性。你可能有一个函数作用于this做些事情,JavaScript的构建方式允许你以特定的方式将该函数应用于任何object。这有点难以描述,但它在诸如inheritance等情况下派上用场。另请参阅:http://trephine.org/t/index.php?title=JavaScript_call_and_apply

1

在Javascript中使用whenever you call a function使用obj.method()表示法,this将被绑定到obj

您可以解决此通过拆分呼叫分成两个单独的步骤:

var f = A.foo; 
f(); // "this" will not be A in this case. 

或者滥用逗号操作符:

(17, x.f)()