这是让我感到困惑的代码片段:
var timer =
{
start: function()
{
var self = this;
/*Why the code below doesn't write to this:
window.setInterval(self.tick, 1000).*/
//Instead, it embedded into a function like this:
window.setInterval(function(){self.tick();}, 1000)
},
tick: function()
{
console.log("tick!");
}
}
timer.start();
原因是 JavaScript 的this
是动态的。当您调用如下函数时:
object.func();
this
将被设置为object
。然而,当你简单地调用一个函数时:
func();
或者将其传递给许多其他函数(setInterval
包括),this
将被设置为全局对象(window
, 通常)。
因此,当你刚刚通过时self.tick
to setInterval
, then this
代替tick
将是全局对象,而不是timer
。当你通过时function() { self.tick(); }
, it is self
(timer
).
在这里,这没有什么区别,因为tick
不访问this
,但如果tick
访问过this
,你可能想使用function() { self.tick(); }
,因为否则,您将修改全局对象的属性,而不是timer
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)