欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript中日常收集常見的10種錯誤(推薦)

 更新時間:2017年01月08日 10:22:08   作者:Tthe_last  
本文是小編給大家日常收集整理的js中常見的10種錯誤,非常不錯,具有參考借鑒價值,需要的朋友參考下

 1 對于this關(guān)鍵詞的不正確使用

Game.prototype.restart = function () { 
this.clearLocalStorage(); 
this.timer = setTimeout (function() { 
this.clearBoard(); 
}, 0); 
};

運(yùn)行上面的代碼將會出現(xiàn)如下錯誤:

uncaught typeError:undefined is not a function

為什么會有這個錯? this是指代當(dāng)前對象本身,this的調(diào)用和它所在的環(huán)境密切相關(guān)。上面的錯誤是因為在調(diào)用setTimeout函數(shù)的時候,實際調(diào)用的是window.setTimeout,而在window中并沒有clearBoard();這個方法;

下面提供兩種解決的方法。

1,將當(dāng)前對象存儲在一個變量中,這樣可以在不同的環(huán)境被繼承。

Game.prototype.restart = function() { 
this.clearLocalStorage(); 
var self = this; 
this.timer = setTimeout(function(){ 
self.clearBoard(); }, 0); 
}; //改變了作用的對象 

2,使用bind()方法, 不過這個相比上一種會復(fù)雜,bind方法官方解釋: msdn.microsoft.com/zh-cn/library/ff841995

Game.prototype.restart = function () { 
this.clearLocalStorage(); 
this.timer = setTimeout(this.reset.bind(this)), 
}; 
Game.prototype.reset = function() { 
this.clearBoard(); 
};

2 傳統(tǒng)編程語言的生命周期誤區(qū)

在js中變量的生存周期與其他語言不同,舉個例子

for (var i=0; i<10;i++){ 
/* */ 
} 
console.log(i); //并不會提示 未定義,結(jié)果是10 

在js中這種現(xiàn)象叫:variable hoisting(聲明提前)

可以使用let關(guān)鍵字。

3 內(nèi)存泄漏

在js中無法避免會有內(nèi)存泄漏,內(nèi)存泄漏:占用的內(nèi)存,但是沒有用也不能及時回收的內(nèi)存。

例如以下函數(shù):

var theThing = null; 
var replaceThing = function() { 
var priorThing = theThing; 
var unused = function() { 
if (priorThing) { 
console.log(‘hi'); 
}; 
}; 
theThing = { 
longStr: new Array(1000000).join(‘*'), 
someMethod: function () { 
console.log(someMessage); 
} 
} 
setInterval(replaceThing, 1000);

如果執(zhí)行這段代碼,會造成大量的內(nèi)存泄漏,光靠garbage collector是無法完成回收的,代碼中有個創(chuàng)建數(shù)組對象的方法在一個閉包里,這個閉包對象又在另一個閉包中引用,,在js語法中規(guī)定,在閉包中引用閉包外部變量,閉包結(jié)束時對此對象無法回收。

4 比較運(yùn)算符

console.log(false == ‘0'); // true 
console.log(null == undefinded); //true 
console.log(” \t\r\n” == 0);

以上所述是小編給大家介紹的JavaScript中日常收集常見的10種錯誤(推薦),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復(fù)大家的!

相關(guān)文章

最新評論