1 對于this關鍵詞的不正確使用
Game.prototype.restart = function () { this.clearLocalStorage(); this.timer = setTimeout (function() { this.clearBoard(); }, 0); };運行上面的代碼將會出現如下錯誤:
uncaught typeError:undefined is not a function
為什么會有這個錯? this是指代當前對象本身,this的調用和它所在的環境密切相關。上面的錯誤是因為在調用setTimeout函數的時候,實際調用的是window.setTimeout,而在window中并沒有clearBoard();這個方法;
下面提供兩種解決的方法。
1,將當前對象存儲在一個變量中,這樣可以在不同的環境被繼承。
Game.prototype.restart = function() { this.clearLocalStorage(); var self = this; this.timer = setTimeout(function(){ self.clearBoard(); }, 0); }; //改變了作用的對象 2,使用bind()方法, 不過這個相比上一種會復雜,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 傳統編程語言的生命周期誤區
在js中變量的生存周期與其他語言不同,舉個例子
for (var i=0; i<10;i++){ /* */ } console.log(i); //并不會提示 未定義,結果是10 在js中這種現象叫:variable hoisting(聲明提前)
可以使用let關鍵字。
3 內存泄漏
在js中無法避免會有內存泄漏,內存泄漏:占用的內存,但是沒有用也不能及時回收的內存。
例如以下函數:
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);如果執行這段代碼,會造成大量的內存泄漏,光靠garbage collector是無法完成回收的,代碼中有個創建數組對象的方法在一個閉包里,這個閉包對象又在另一個閉包中引用,,在js語法中規定,在閉包中引用閉包外部變量,閉包結束時對此對象無法回收。
4 比較運算符
console.log(false == ‘0'); // true console.log(null == undefinded); //true console.log(” /t/r/n” == 0);
以上所述是小編給大家介紹的JavaScript中日常收集常見的10種錯誤(推薦),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
新聞熱點
疑難解答