简体   繁体   English

为什么在setTimeout中调用此方法时不引用窗口

[英]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的实例,它的值设置thisme该函数内部。 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直接,而不是作为一个属性methis将涉及到该窗口。

For example: 例如:

var getName = me.getName;
alert (getName ())

or 要么

alert (me.getName.call (this))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM