開發人員最容易犯的13個JavaScript錯誤

來源:互聯網
上載者:User

開發人員最容易犯的JavaScript錯誤,總結出13個。這些當中可能少不了你犯的錯誤。我們描述了這些陋習,並列出來解決辦法,希望對開發人員有協助。

1.for...數組迭代的用法 Usage of for..in to iterate Arrays

舉例:

  1. var myArray = [ “a”, “b”, “c” ];   
  2. var totalElements = myArray.length;   
  3. for (var i = 0; i < totalElements; i++) {   
  4. console.log(myArray[i]);   
  5. }   

這裡主要的問題是語句中的“for..."不能保證順序,這意味著你將獲得不同的執行結果。此外,如果有人增加一些其他自訂功能的函數Array.prototype,你的迴圈將重複遍曆這些函數,就像原數組項。

解決辦法:一直使用規則的for迴圈來遍曆數組。

  1. var myArray = [ “a”, “b”, “c” ];   
  2. for (var i=0; i<myArray.length; i++) {   
  3. console.log(myArray[i]);   
  4. }   

2.數組維度Array dimensions

舉例

  1. var myArray = new Array(10);  

第二個問題是開發人員使用數組構成器來建立數組,技術上是正確的,然而會比文字元號(literal notation)慢解決辦法:使用文字元號來初始化數組,不要預定義數組長度。

  1. var myArray = []; 

3.未定義屬性 Undefined properties

舉例:

  1. var myObject = {   
  2.     someProperty: “value”,   
  3.     someOtherProperty: undefined   
  4. }  

未定義屬性,將在對象中建立元素(鍵‘someOtherProperty’和值‘undefined’.)。如果你遍曆數組,檢測已存在的元素,那麼下面的語句將都返回“未定義/undefined”

  1. typeof myObject['someOtherProperty'] // undefined   
  2.   
  3. typeof myObject['unknownProperty'] // undefined   

解決辦法:如果你想明確聲明對象中的未初始化的屬性,標記它們為Null(空)。

  1. var myObject = {   
  2. someProperty: “value”,   
  3. someOtherProperty: null   
  4. }  

4.閉包的濫用Misuse of Closures

舉例:

  1. function(a, b, c) {   
  2. var d = 10;   
  3. var element = document.getElementById(‘myID’);   
  4. element.onclick = (function(a, b, c, d) {   
  5. return function() {   
  6. alert (a + b + c + d);   
  7. }   
  8. })(a, b, c, d);   
  9. }   

這裡開發人員使用兩個函數來傳遞參數a、b、c到onclick handler。雙函數根本不需要,徒增代碼的複雜性。

變數abc已經在局部函數中被定義,因為他們已經在主函數中作為參數被聲明。局部函數中的任何函數都可建立主函數中定義的所有變數的閉包。因此不需要再次傳遞它們。

看看這裡JavaScript Closures FAQ瞭解更多。

解決辦法:使用閉環來簡化你的代碼。

  1. function (a, b, c) {   
  2. var d = 10;   
  3. var element = document.getElementById(‘myID’);   
  4. element.onclick = function() {   
  5. //a, b, and c come from the outer function arguments.   
  6. //d come from the outer function variable declarations.   
  7. //and all of them are in my closure   
  8. alert (a + b + c + d);   
  9. };   
  10. }   

5.迴圈中的閉包Closures in loops

舉例:

  1. var elements = document.getElementByTagName(‘div’);   
  2. for (var i = 0; i<elements.length; i++) {   
  3. elements[i].onclick = function() {   
  4. alert(“Div number “ + i);   
  5. }   
  6. }   

在這裡例子裡面,當使用者點擊不同的divs時,我們想觸發一個動作(顯示“Div number 1”, “Div number 2”… 等) 。然而,如果你在頁面有10個divs,他們全部都會顯示“Div number 10”。

問題是當我們使用局部函數建立一個閉包時,函數中的代碼可以訪問變數i。關鍵是函數內部i和函數外部i涉及同樣的變數。當我們的迴圈結束,i指向了值10,所以局部函數中的i的值將是10。

解決辦法:使用第二函數來傳遞正確的值。

  1. var elements = document.getElementsByTagName(‘div’);   
  2. for (var i = 0; i<elements.length; i++) {   
  3. elements[i].onclick = (function(idx) { //Outer function   
  4. return function() { //Inner function   
  5. alert(“Div number “ + idx);   
  6. }   
  7. })(i);   
  8. }   

6.DOM對象的內測泄漏Memory leaks with DOM objects

舉例:

  1. function attachEvents() {   
  2. var element = document.getElementById(‘myID’);   
  3. element.onclick = function() {   
  4. alert(“Element clicked”);   
  5. }   
  6. };   
  7. attachEvents();   

該代碼建立了一個引用迴圈。變數元素包含函數的引用(歸於onclick屬性)。同時,函數保持一個DOM元素的引用(提示函數內部可以訪問元素, 因為閉包。)。所以JavaScript垃圾收集器不能清除元素或是函數,因為他們被相互引用。大部分的JavaScript引擎對於清除迴圈應用都不夠 聰明。

解決辦法:避免那些閉包,或者不去做函數內的循環參考。

  1. function attachEvents() {   
  2. var element = document.getElementById(‘myID’);   
  3. element.onclick = function() {   
  4. //Remove element, so function can be collected by GC   
  5. delete element;   
  6. alert(“Element clicked”);   
  7. }   
  8. };   
  9. attachEvents(); 

7.區別整數數字和浮點數字Differentiate float numbers from integer numbers

舉例:

  1. var myNumber = 3.5;   
  2. var myResult = 3.5 + 1.0; //We use .0 to keep the result as float   

在JavaScript中,浮點與整數間沒有區別。事實上,JavaScript中的每個數字都表示使用雙精確度64位格式IEEE 754。簡單理解,所有數字都是浮點。

解決辦法:不要使用小數(decimals),轉換數字(numbers)到浮點(floats)。

  1. var myNumber = 3.5;   
  2. var myResult = 3.5 + 1; //Result is 4.5, as expected   

8.with()作為捷徑的用法Usage of with() as a shortcut

舉例:

  1. team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};   
  2. with (team.attackers.myWarrior){   
  3. console.log ( “Your warrior power is ” + (attack * speed));   
  4. }   

討論with()之前,要明白JavaScript contexts如何工作的。每個函數都有一個執行context(語句),簡單來說,包括函數可以訪問的所有的變數。因此context包含arguments和定義變數。

with()真正是做什嗎?是插入對象到context鏈,它在當前context和父級context間植入。就像你看到的with()的捷徑會非常慢。

解決辦法:不要使用with() for shortcuts,僅for context injection,如果你確實需要時。

  1. team.attackers.myWarrior = { attack: 1, speed: 3, magic: 5};   
  2. var sc = team.attackers.myWarrior;   
  3. console.log(“Your warrior power is ” + (sc.attack * sc.speed)); 

9.setTimeout/setInterval 字串的用法 Usage of strings with setTimeout/setInterval

舉例:

  1. function log1() { console.log(document.location); }   
  2. function log2(arg) { console.log(arg); }   
  3. var myValue = “test”;   
  4. setTimeout(“log1()”, 100);   
  5. setTimeout(“log2(” + myValue + “)”, 200);   

setTimeout()和setInterval()可被或一個函數或一個字串作為首個參數。如果你傳遞一個字串,引擎將建立一個新函數(使用函數構造器),這在一些瀏覽器中會非常慢。相反,傳遞函數本身作為首個參數,更快、更強大、更乾淨。

解決辦法:一定不要使用strings for setTimeout()或setInterval()。

  1. function log1() { console.log(document.location); }   
  2. function log2(arg) { console.log(arg); }   
  3. var myValue = “test”;   
  4. setTimeout(log1, 100); //Reference to a function   
  5. setTimeout(function(){ //Get arg value using closures   
  6. log2(arg);   
  7. }, 200);   

10.setInterval()的用法Usage of setInterval() for heavy functions

舉例:

  1. function domOperations() {   
  2. //Heavy DOM operations, takes about 300ms   
  3. }   
  4. setInterval(domOperations, 200);   

setInterval()將一函數列入計劃被執行,僅是在沒有另外一個執行在主執行隊列中等待。JavaScript引擎只增加下一個執行到隊列如果沒有另外一個執行已在隊列。這可能導致跳過執行或者運行2個不同的執行,沒有在它們之間等待200ms的情況下。

一定要搞清,setInterval()沒有考慮進多長時間domOperations()來完成任務。

解決辦法:避免 setInterval(),使用 setTimeout()

  1. function domOperations() {   
  2. //Heavy DOM operations, takes about 300ms   
  3. //After all the job is done, set another timeout for 200 ms   
  4. setTimeout(domOperations, 200);   
  5. }   
  6. setTimeout(domOperations, 200);   

11.“this”的濫用Misuse of ‘this’

這個常用錯誤,沒有例子,因為非常難建立來示範。this的值在JavaScript中與其他語言有很大的不同。

函數中的this值被定義是在當函數被調用時,而非聲明的時間,這一點非常重要。下面的案例中,函數內this有不同的含義。

* Regular function: myFunction(‘arg1’);

this points to the global object, wich is window for all browers.

* Method: someObject.myFunction(‘arg1’);

this points to object before the dot, someObject in this case.

* Constructor: var something = new myFunction(‘arg1’);

this points to an empty Object.

* Using call()/apply(): myFunction.call(someObject, ‘arg1’);

this points to the object passed as first argument.

12.eval()訪問動態屬性的用法Usage of eval() to access dynamic properties

舉例:

  1. var myObject = { p1: 1, p2: 2, p3: 3};   
  2. var i = 2;   
  3. var myResult = eval(‘myObject.p’+i);   

主要問題在於使用eval()開始一個新的執行語句,會非常的慢。

解決辦法:使用方括弧標記法(square bracket notation)代替 eval()。

  1. var myObject = { p1: 1, p2: 2, p3: 3};   
  2. var i = 2;   
  3. var myResult = myObject[“p”+i];   

13.未定義(undefined)作為變數的用法Usage of undefined as a variable

舉例:

  1. if ( myVar === undefined ) {   
  2. //Do something   
  3. }   

在上面的例子中,未定義實際上是一變數。所有的JavaScript引擎會建立初始化的變數window.undefined給未定義作為值。然而注意的 是變數不僅是可讀,任何其他的代碼可以剛改它的值。很奇怪能找到window.undefined有來自未定義的不同的值的情境,但是為什麼冒險呢?

解決辦法:檢查未定義時,使用typeof。

  1. if ( typeof myVar === “undefined” ) {   
  2. //Do something   
  3. }   

轉自http://www.aspxcs.net/HTML/0009273657.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.