在闭包或回调中,this
关键字的作用域很容易弄错。举个例子:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(function() {
this.clearBoard(); // 此处this指的是?
}, 0);
};
如果执行上面的代码,我们会看到报错:
Uncaught TypeError: undefined is not a function
出错的原因在于:当你调用setTimeout
函数,你实际上调用的是window.setTimeout()
。在setTimeout
中传入的匿名函数是在window
这个对象环境下,所以this
是指向window
,但是window
并没有clearBoard
方法。
如何解决呢?定义新的变量引用指向Game
对象的this
,然后就可以使用啦。
Game.prototype.restart = function () {
this.clearLocalStorage();
var self = this; // 将this指向的对象绑定到self
this.timer = setTimeout(function(){
self.clearBoard();
}, 0);
};
或则使用bind()
函数:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(this.reset.bind(this), 0); // bind to 'this'
};
Game.prototype.reset = function(){
this.clearBoard(); // 此处this的引用正确
};