前端編碼風格規範之 JavaScript 規範,前端javascript

來源:互聯網
上載者:User

前端編碼風格規範之 JavaScript 規範,前端javascript
JavaScript 規範全域命名空間汙染與 IIFE

總是將程式碼封裝裹成一個 IIFE(Immediately-Invoked Function Expression),用以建立獨立隔絕的定義域。這一舉措可防止全域命名空間被汙染。

IIFE 還可確保你的代碼不會輕易被其它全域命名空間裡的代碼所修改(i.e. 第三方庫,window 引用,被覆蓋的未定義的關鍵字等等)。

不推薦

var x = 10,    y = 100;// Declaring variables in the global scope is resulting in global scope pollution. All variables declared like this// will be stored in the window object. This is very unclean and needs to be avoided.console.log(window.x + ' ' + window.y);

推薦

// We declare a IIFE and pass parameters into the function that we will use from the global space(function(log, w, undefined){  'use strict';  var x = 10,      y = 100;  // Will output 'true true'  log((w.x === undefined) + ' ' + (w.y === undefined));}(window.console.log, window));
IIFE(立即執行的函數運算式)

無論何時,想要建立一個新的封閉的定義域,那就用 IIFE。它不僅避免了幹擾,也使得記憶體在執行完後立即釋放。

所有指令檔建議都從 IIFE 開始。

立即執行的函數運算式的執行括弧應該寫在外包括弧內。雖然寫在內還是寫在外都是有效,但寫在內使得整個運算式看起來更像一個整體,因此推薦這麼做。

不推薦

(function(){})();

推薦

(function(){}());

so,用下列寫法來格式化你的 IIFE 代碼:

(function(){  'use strict';  // Code goes here}());

如果你想引用全域變數或者是外層 IIFE 的變數,可以通過下列方式傳參:

(function($, w, d){  'use strict';  $(function() {    w.alert(d.querySelectorAll('div').length);  });}(jQuery, window, document));
嚴格模式

ECMAScript 5 嚴格模式可在整個指令碼或獨個方法內被啟用。它對應不同的 javascript 語境會做更加嚴格的錯誤檢查。嚴格模式也確保了 javascript 代碼更加的健壯,啟動並執行也更加快速。

嚴格模式會阻止使用在未來很可能被引入的預留關鍵字。

你應該在你的指令碼中啟用嚴格模式,最好是在獨立的 IIFE 中應用它。避免在你的指令碼第一行使用它而導致你的所有指令碼都啟動了嚴格模式,這有可能會引發一些第三方類庫的問題。

不推薦

// Script starts here'use strict';(function(){  // Your code starts here}());

推薦

(function(){  'use strict';  // Your code starts here}());
變數聲明

總是使用 var 來聲明變數。如不指定 var,變數將被隱式地聲明為全域變數,這將對變數難以控制。如果沒有聲明,變數處於什麼定義域就變得不清(可以是在 Document 或 Window 中,也可以很容易地進入本地定義域)。所以,請總是使用 var 來聲明變數。

採用嚴格模式帶來的好處是,當你手誤輸入錯誤的變數名時,它可以通過報錯資訊來協助你定位錯誤出處。

不推

x = 10;y = 100;

推薦

var x = 10,    y = 100;
理解 JavaScript 的定義域和定義域提升

在 JavaScript 中變數和方法定義會自動提升到執行之前。JavaScript 只有 function 級的定義域,而無其他很多程式設計語言中的塊定義域,所以使得你在某一 function 內的某語句和迴圈體中定義了一個變數,此變數可作用於整個 function 內,而不僅僅是在此語句或迴圈體中,因為它們的聲明被 JavaScript 自動提升了。

我們通過例子來看清楚這到底是怎麼一回事:

原 function

(function(log){  'use strict';  var a = 10;  for(var i = 0; i < a; i++) {    var b = i * i;    log(b);  }  if(a === 10) {    var f = function() {      log(a);    };    f();  }  function x() {    log('Mr. X!');  }  x();}(window.console.log));

被 JS 提升過後

(function(log){  'use strict';  // All variables used in the closure will be hoisted to the top of the function  var a,      i,      b,      f;  // All functions in the closure will be hoisted to the top  function x() {    log('Mr. X!');  }  a = 10;  for(i = 0; i < a; i++) {    b = i * i;    log(b);  }  if(a === 10) {    // Function assignments will only result in hoisted variables but the function body will not be hoisted    // Only by using a real function declaration the whole function will be hoisted with its body    f = function() {      log(a);    };    f();  }  x();}(window.console.log));

根據以上提升過程,你是否可理解以下代碼?

有效代碼

(function(log){  'use strict';  var a = 10;  i = 5;  x();  for(var i; i < a; i++) {    log(b);    var b = i * i;  }  if(a === 10) {    f = function() {      log(a);    };    f();    var f;  }  function x() {    log('Mr. X!');  }}(window.console.log));

正如你所看到的這段令人充滿困惑與誤解的代碼導致了出人意料的結果。只有良好的聲明習慣,也就是下一章節我們要提到的聲明規則,才能儘可能的避免這類錯誤風險。

提升聲明

為避免上一章節所述的變數和方法定義被自動提升造成誤解,把風險降到最低,我們應該手動地顯示地去聲明變數與方法。也就是說,所有的變數以及方法,應當定義在 function 內的首行。

只用一個 var 關鍵字聲明,多個變數用逗號隔開。

不推薦

(function(log){  'use strict';  var a = 10;  var b = 10;  for(var i = 0; i < 10; i++) {    var c = a * b * i;  }  function f() {  }  var d = 100;  var x = function() {    return d * d;  };  log(x());}(window.console.log));

推薦

(function(log){  'use strict';  var a = 10,      b = 10,      i,      c,      d,      x;  function f() {  }  for(i = 0; i < 10; i++) {    c = a * b * i;  }  d = 100;  x = function() {    return d * d;  };  log(x());}(window.console.log));

把賦值盡量寫在變數申明中。

不推薦

var a,    b,    c;a = 10;b = 10;c = 100;

推薦

var a = 10,    b = 10,    c = 100;
總是使用帶類型判斷的比較判斷

總是使用 === 精確的比較操作符,避免在判斷的過程中,由 JavaScript 的強制類型轉換所造成的困擾。

如果你使用 === 操作符,那比較的雙方必須是同一類型為前提的條件下才會有效。

如果你想瞭解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.