javaScript中this的常见问题

在闭包或回调中,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的引用正确
};

你可能感兴趣的:(javaScript中this的常见问题)