划重点
如今网站几乎100%使用JavaScript。JavaScript看上去是一门十分简单的语言,然而事实并不如此。它有很多容易被弄错的细节,一不注意就导致BUG。今天分享10JavaScript常见的bug及修改方法,详见下文
1、错误的对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的引用正确
};
2、和块作用域