[英]Why isn't this referring to window when called in setTimeout
If there is no binding of functions to instances in javascript how does getName()
return john
如果没有函数绑定到javascript中的实例,
getName()
如何返回john
function Person() {
this.name = "john";
this.getName = function() {
return this.name;
};
}
var me = new Person();
setTimeout(function(){alert(me.getName())}, 3000);
I though this
would refer to the window at the point of call from setTimeout
. 我虽然
this
是指setTimeout
调用时的窗口。
See jsFiddle: http://jsfiddle.net/qZeXG/ 参见jsFiddle: http : //jsfiddle.net/qZeXG/
What's happening here is that the anonymous function executed by setTimeout
closes over the me
variable, which is a Person
instance. 这里发生的是由
setTimeout
执行的匿名函数关闭了me
变量,这是一个Person
实例。 Because of closure, you can still reference me
when that function is later called. 由于闭包,以后调用该函数时仍可以引用
me
。
When you invoke me.getName()
you're invoking a method on the Person
instance, which sets the value of this
to me
inside that function. 当你调用
me.getName()
你调用的是一个方法Person
的实例,它的值设置this
对me
该函数内部。 This is just a normal method invocation. 这只是正常的方法调用。
Note that in the following code: 请注意以下代码:
var me = new Person();
setTimeout(function() {
alert(this);
alert(me.getName());
}, 3000);
...the value of this
in the first alert
is the window
object. ...的值
this
第一alert
是 window
对象。 It's the ordinary method invocation that is changing the value. 改变值的是普通方法调用。
Consider this final example: 考虑这个最后的例子:
var me = new Person();
var getName = me.getName;
setTimeout(function(){ alert(getName()) }, 3000);
In this case the function also closes over a reference to getName
, but the function that that variable points to is invoked without any information about the Person
instance it came from. 在这种情况下,该函数还会关闭对
getName
的引用,但是调用该变量所指向的函数时,将不会获得有关它来自的Person
实例的任何信息。 Therefore, the value of this
inside getName
will be the window
object. 因此,在
getName
内部的this
的值将是window
对象。
Conclusion? 结论? This statement:
这个说法:
...there is no binding of functions to instances in javascript...
...没有功能绑定到javascript中的实例...
...is a false assumption. ...是一个错误的假设。
this
will be the Person instance, because you called getName
on the me
object. this
将是Person实例,因为您在me
对象上调用了getName
。
If you just called getName
directly and not as a property of me
, this
would refer to the window. 如果你只是叫
getName
直接,而不是作为一个属性me
, this
将涉及到该窗口。
For example: 例如:
var getName = me.getName;
alert (getName ())
or 要么
alert (me.getName.call (this))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.