久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

前端編碼風(fēng)格規(guī)范之 JavaScript 規(guī)范

JavaScript 只有 function 級(jí)的定義域,而無(wú)其他很多編程語(yǔ)言中的塊定義域,所以使得你在某一 function 內(nèi)的某語(yǔ)句和循環(huán)體中定義了一個(gè)變量,此變量可作用于整個(gè) function 內(nèi),而不僅僅是在
英文原文:Web Styleguide - Style guide to harmonize HTML, Javascript and CSS / SASS coding style


JavaScript 規(guī)范


全局命名空間污染與 IIFE


總是將代碼包裹成一個(gè) IIFE(Immediately-Invoked Function Expression),用以創(chuàng)建獨(dú)立隔絕的定義域。這一舉措可防止全局命名空間被污染。


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


不推薦


  1. var x = 10,
  2.     y = 100;

  3. // Declaring variables in the global scope is resulting in global scope pollution. All variables declared like this
  4. // will be stored in the window object. This is very unclean and needs to be avoided.
  5. console.log(window.x + ' ' + window.y);
復(fù)制代碼


推薦


  1. // We declare a IIFE and pass parameters into the function that we will use from the global space
  2. (function(log, w, undefined){
  3.   'use strict';

  4.   var x = 10,
  5.       y = 100;

  6.   // Will output 'true true'
  7.   log((w.x === undefined) + ' ' + (w.y === undefined));

  8. }(window.console.log, window));
復(fù)制代碼


IIFE(立即執(zhí)行的函數(shù)表達(dá)式)


無(wú)論何時(shí),想要?jiǎng)?chuàng)建一個(gè)新的封閉的定義域,那就用 IIFE。它不僅避免了干擾,也使得內(nèi)存在執(zhí)行完后立即釋放。


所有腳本文件建議都從 IIFE 開始。


立即執(zhí)行的函數(shù)表達(dá)式的執(zhí)行括號(hào)應(yīng)該寫在外包括號(hào)內(nèi)。雖然寫在內(nèi)還是寫在外都是有效的,但寫在內(nèi)使得整個(gè)表達(dá)式看起來(lái)更像一個(gè)整體,因此推薦這么做。


不推薦


  1. (function(){})();
復(fù)制代碼


推薦


  1. (function(){}());
復(fù)制代碼


so,用下列寫法來(lái)格式化你的 IIFE 代碼:


  1. (function(){
  2.   'use strict';

  3.   // Code goes here

  4. }());
復(fù)制代碼


如果你想引用全局變量或者是外層 IIFE 的變量,可以通過(guò)下列方式傳參:


  1. (function($, w, d){
  2.   'use strict';

  3.   $(function() {
  4.     w.alert(d.querySelectorAll('div').length);
  5.   });
  6. }(jQuery, window, document));
復(fù)制代碼


嚴(yán)格模式


ECMAScript 5 嚴(yán)格模式可在整個(gè)腳本或獨(dú)個(gè)方法內(nèi)被激活。它對(duì)應(yīng)不同的 javascript 語(yǔ)境會(huì)做更加嚴(yán)格的錯(cuò)誤檢查。嚴(yán)格模式也確保了 javascript 代碼更加的健壯,運(yùn)行的也更加快速。


嚴(yán)格模式會(huì)阻止使用在未來(lái)很可能被引入的預(yù)留關(guān)鍵字。


你應(yīng)該在你的腳本中啟用嚴(yán)格模式,最好是在獨(dú)立的 IIFE 中應(yīng)用它。避免在你的腳本第一行使用它而導(dǎo)致你的所有腳本都啟動(dòng)了嚴(yán)格模式,這有可能會(huì)引發(fā)一些第三方類庫(kù)的問(wèn)題。


不推薦


  1. // Script starts here
  2. 'use strict';

  3. (function(){

  4.   // Your code starts here

  5. }());
  6. 推薦

  7. (function(){
  8.   'use strict';

  9.   // Your code starts here

  10. }());
復(fù)制代碼


變量聲明


總是使用 var 來(lái)聲明變量。如不指定 var,變量將被隱式地聲明為全局變量,這將對(duì)變量難以控制。如果沒有聲明,變量處于什么定義域就變得不清(可以是在 Document 或 Window 中,也可以很容易地進(jìn)入本地定義域)。所以,請(qǐng)總是使用 var 來(lái)聲明變量。


采用嚴(yán)格模式帶來(lái)的好處是,當(dāng)你手誤輸入錯(cuò)誤的變量名時(shí),它可以通過(guò)報(bào)錯(cuò)信息來(lái)幫助你定位錯(cuò)誤出處。


不推


  1. x = 10;
  2. y = 100;
復(fù)制代碼


推薦


  1. var x = 10,
  2.     y = 100;
復(fù)制代碼


理解 JavaScript 的定義域和定義域提升


在 JavaScript 中變量和方法定義會(huì)自動(dòng)提升到執(zhí)行之前。JavaScript 只有 function 級(jí)的定義域,而無(wú)其他很多編程語(yǔ)言中的塊定義域,所以使得你在某一 function 內(nèi)的某語(yǔ)句和循環(huán)體中定義了一個(gè)變量,此變量可作用于整個(gè) function 內(nèi),而不僅僅是在此語(yǔ)句或循環(huán)體中,因?yàn)樗鼈兊穆暶鞅?JavaScript 自動(dòng)提升了。


我們通過(guò)例子來(lái)看清楚這到底是怎么一回事:


原 function


  1. (function(log){
  2.   'use strict';

  3.   var a = 10;

  4.   for(var i = 0; i < a; i++) {
  5.     var b = i * i;
  6.     log(b);
  7.   }

  8.   if(a === 10) {
  9.     var f = function() {
  10.       log(a);
  11.     };
  12.     f();
  13.   }

  14.   function x() {
  15.     log('Mr. X!');
  16.   }
  17.   x();

  18. }(window.console.log));
復(fù)制代碼


被 JS 提升過(guò)后


  1. (function(log){
  2.   'use strict';
  3.   // All variables used in the closure will be hoisted to the top of the function
  4.   var a,
  5.       i,
  6.       b,
  7.       f;
  8.   // All functions in the closure will be hoisted to the top
  9.   function x() {
  10.     log('Mr. X!');
  11.   }

  12.   a = 10;

  13.   for(i = 0; i < a; i++) {
  14.     b = i * i;
  15.     log(b);
  16.   }

  17.   if(a === 10) {
  18.     // Function assignments will only result in hoisted variables but the function body will not be hoisted
  19.     // Only by using a real function declaration the whole function will be hoisted with its body
  20.     f = function() {
  21.       log(a);
  22.     };
  23.     f();
  24.   }

  25.   x();

  26. }(window.console.log));
復(fù)制代碼


根據(jù)以上提升過(guò)程,你是否可理解以下代碼?


有效代碼


  1. (function(log){
  2.   'use strict';

  3.   var a = 10;

  4.   i = 5;

  5.   x();

  6.   for(var i; i < a; i++) {
  7.     log(b);
  8.     var b = i * i;
  9.   }

  10.   if(a === 10) {
  11.     f = function() {
  12.       log(a);
  13.     };
  14.     f();

  15.     var f;
  16.   }

  17.   function x() {
  18.     log('Mr. X!');
  19.   }

  20. }(window.console.log));
復(fù)制代碼


正如你所看到的這段令人充滿困惑與誤解的代碼導(dǎo)致了出人意料的結(jié)果。只有良好的聲明習(xí)慣,也就是下一章節(jié)我們要提到的聲明規(guī)則,才能盡可能的避免這類錯(cuò)誤風(fēng)險(xiǎn)。


提升聲明


為避免上一章節(jié)所述的變量和方法定義被自動(dòng)提升造成誤解,把風(fēng)險(xiǎn)降到最低,我們應(yīng)該手動(dòng)地顯示地去聲明變量與方法。也就是說(shuō),所有的變量以及方法,應(yīng)當(dāng)定義在 function 內(nèi)的首行。


只用一個(gè) var 關(guān)鍵字聲明,多個(gè)變量用逗號(hào)隔開。


不推薦


  1. (function(log){
  2.   'use strict';

  3.   var a = 10;
  4.   var b = 10;

  5.   for(var i = 0; i < 10; i++) {
  6.     var c = a * b * i;
  7.   }

  8.   function f() {

  9.   }

  10.   var d = 100;
  11.   var x = function() {
  12.     return d * d;
  13.   };
  14.   log(x());

  15. }(window.console.log));
復(fù)制代碼


推薦


  1. (function(log){
  2.   'use strict';

  3.   var a = 10,
  4.       b = 10,
  5.       i,
  6.       c,
  7.       d,
  8.       x;

  9.   function f() {

  10.   }

  11.   for(i = 0; i < 10; i++) {
  12.     c = a * b * i;
  13.   }



  14.   d = 100;
  15.   x = function() {
  16.     return d * d;
  17.   };
  18.   log(x());

  19. }(window.console.log));
復(fù)制代碼


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


不推薦


  1. var a,
  2.     b,
  3.     c;

  4. a = 10;
  5. b = 10;
  6. c = 100;
復(fù)制代碼


推薦


  1. var a = 10,
  2.     b = 10,
  3.     c = 100;
復(fù)制代碼


總是使用帶類型判斷的比較判斷


總是使用 === 精確的比較操作符,避免在判斷的過(guò)程中,由 JavaScript 的強(qiáng)制類型轉(zhuǎn)換所造成的困擾。


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


如果你想了解更多關(guān)于強(qiáng)制類型轉(zhuǎn)換的信息,你可以讀一讀 Dmitry Soshnikov 的這篇文章。


在只使用 == 的情況下,JavaScript 所帶來(lái)的強(qiáng)制類型轉(zhuǎn)換使得判斷結(jié)果跟蹤變得復(fù)雜,下面的例子可以看出這樣的結(jié)果有多怪了:


  1. (function(log){
  2.   'use strict';

  3.   log('0' == 0); // true
  4.   log('' == false); // true
  5.   log('1' == true); // true
  6.   log(null == undefined); // true

  7.   var x = {
  8.     valueOf: function() {
  9.       return 'X';
  10.     }
  11.   };

  12.   log(x == 'X');

  13. }(window.console.log));
復(fù)制代碼


明智地使用真假判斷


當(dāng)我們?cè)谝粋€(gè) if 條件語(yǔ)句中使用變量或表達(dá)式時(shí),會(huì)做真假判斷。if(a == true) 是不同于 if(a) 的。后者的判斷比較特殊,我們稱其為真假判斷。這種判斷會(huì)通過(guò)特殊的操作將其轉(zhuǎn)換為 true 或 false,下列表達(dá)式統(tǒng)統(tǒng)返回 false:false, 0, undefined, null, NaN, ''(空字符串).


這種真假判斷在我們只求結(jié)果而不關(guān)心過(guò)程的情況下,非常的有幫助。


以下示例展示了真假判斷是如何工作的:


  1. (function(log){
  2.   'use strict';

  3.   function logTruthyFalsy(expr) {
  4.     if(expr) {
  5.       log('truthy');
  6.     } else {
  7.       log('falsy');
  8.     }
  9.   }

  10.   logTruthyFalsy(true); // truthy
  11.   logTruthyFalsy(1); // truthy
  12.   logTruthyFalsy({}); // truthy
  13.   logTruthyFalsy([]); // truthy
  14.   logTruthyFalsy('0'); // truthy

  15.   logTruthyFalsy(false); // falsy
  16.   logTruthyFalsy(0); // falsy
  17.   logTruthyFalsy(undefined); // falsy
  18.   logTruthyFalsy(null); // falsy
  19.   logTruthyFalsy(NaN); // falsy
  20.   logTruthyFalsy(''); // falsy

  21. }(window.console.log));
復(fù)制代碼


變量賦值時(shí)的邏輯操作


邏輯操作符 || 和 && 也可被用來(lái)返回布爾值。如果操作對(duì)象為非布爾對(duì)象,那每個(gè)表達(dá)式將會(huì)被自左向右地做真假判斷。基于此操作,最終總有一個(gè)表達(dá)式被返回回來(lái)。這在變量賦值時(shí),是可以用來(lái)簡(jiǎn)化你的代碼的。


不推薦


  1. if(!x) {
  2.   if(!y) {
  3.     x = 1;
  4.   } else {
  5.     x = y;
  6.   }
  7. }
復(fù)制代碼


推薦


  1. x = x || y || 1;
復(fù)制代碼


這一小技巧經(jīng)常用來(lái)給方法設(shè)定默認(rèn)的參數(shù)。


  1. (function(log){
  2.   'use strict';

  3.   function multiply(a, b) {
  4.     a = a || 1;
  5.     b = b || 1;

  6.     log('Result ' + a * b);
  7.   }

  8.   multiply(); // Result 1
  9.   multiply(10); // Result 10
  10.   multiply(3, NaN); // Result 3
  11.   multiply(9, 5); // Result 45

  12. }(window.console.log));
復(fù)制代碼


分號(hào)


總是使用分號(hào),因?yàn)殡[式的代碼嵌套會(huì)引發(fā)難以察覺的問(wèn)題。當(dāng)然我們更要從根本上來(lái)杜絕這些問(wèn)題[1] 。以下幾個(gè)示例展示了缺少分號(hào)的危害:


  1. // 1.
  2. MyClass.prototype.myMethod = function() {
  3.   return 42;
  4. }  // No semicolon here.

  5. (function() {
  6.   // Some initialization code wrapped in a function to create a scope for locals.
  7. })();


  8. var x = {
  9.   'i': 1,
  10.   'j': 2
  11. }  // No semicolon here.

  12. // 2.  Trying to do one thing on Internet Explorer and another on Firefox.
  13. // I know you'd never write code like this, but throw me a bone.
  14. [ffVersion, ieVersion][isIE]();


  15. var THINGS_TO_EAT = [apples, oysters, sprayOnCheese]  // No semicolon here.

  16. // 3. conditional execution a la bash
  17. -1 == resultOfOperation() || die();
復(fù)制代碼


So what happens?


JavaScript 錯(cuò)誤 —— 首先返回 42 的那個(gè) function 被第二個(gè) function 當(dāng)中參數(shù)傳入調(diào)用,接著數(shù)字 42 也被“調(diào)用”而導(dǎo)致出錯(cuò)。
八成你會(huì)得到 ‘no such property in undefined’ 的錯(cuò)誤提示,因?yàn)樵谡鎸?shí)環(huán)境中的調(diào)用是這個(gè)樣子:x[ffVersion, ieVersion][isIE]().
die 總是被調(diào)用。因?yàn)閿?shù)組減 1 的結(jié)果是 NaN,它不等于任何東西(無(wú)論 resultOfOperation 是否返回 NaN)。所以最終的結(jié)果是die() 執(zhí)行完所獲得值將賦給 THINGS_TO_EAT.


Why?


JavaScript 中語(yǔ)句要以分號(hào)結(jié)束,否則它將會(huì)繼續(xù)執(zhí)行下去,不管換不換行。以上的每一個(gè)示例中,函數(shù)聲明或?qū)ο蠡驍?shù)組,都變成了在一句語(yǔ)句體內(nèi)。要知道閉合圓括號(hào)并不代表語(yǔ)句結(jié)束,JavaScript 不會(huì)終結(jié)語(yǔ)句,除非它的下一個(gè) token 是一個(gè)中綴符[2] 或者是圓括號(hào)操作符。


這真是讓人大吃一驚,所以乖乖地給語(yǔ)句末加上分號(hào)吧。


澄清:分號(hào)與函數(shù)


分號(hào)需要用在表達(dá)式的結(jié)尾,而并非函數(shù)聲明的結(jié)尾。區(qū)分它們最好的例子是:


  1. var foo = function() {
  2.   return true;
  3. };  // semicolon here.

  4. function foo() {
  5.   return true;
  6. }  // no semicolon here.
復(fù)制代碼


嵌套函數(shù)


嵌套函數(shù)是非常有用的,比如用在持續(xù)創(chuàng)建和隱藏輔助函數(shù)的任務(wù)中。你可以非常自由隨意地使用它們。


語(yǔ)句塊內(nèi)的函數(shù)聲明


切勿在語(yǔ)句塊內(nèi)聲明函數(shù),在 ECMAScript 5 的嚴(yán)格模式下,這是不合法的。函數(shù)聲明應(yīng)該在定義域的頂層。但在語(yǔ)句塊內(nèi)可將函數(shù)申明轉(zhuǎn)化為函數(shù)表達(dá)式賦值給變量。


不推薦


  1. if (x) {
  2.   function foo() {}
  3. }
復(fù)制代碼


推薦


  1. if (x) {
  2.   var foo = function() {};
  3. }
復(fù)制代碼


異常


基本上你無(wú)法避免出現(xiàn)異常,特別是在做大型開發(fā)時(shí)(使用應(yīng)用開發(fā)框架等等)。


在沒有自定義異常的情況下,從有返回值的函數(shù)中返回錯(cuò)誤信息一定非常的棘手,更別提多不優(yōu)雅了。不好的解決方案包括了傳第一個(gè)引用類型來(lái)接納錯(cuò)誤信息,或總是返回一個(gè)對(duì)象列表,其中包含著可能的錯(cuò)誤對(duì)象。以上方式基本上是比較簡(jiǎn)陋的異常處理方式。適時(shí)可做自定義異常處理。


在復(fù)雜的環(huán)境中,你可以考慮拋出對(duì)象而不僅僅是字符串(默認(rèn)的拋出值)。


  1. if(name === undefined) {
  2.   throw {
  3.     name: 'System Error',
  4.     message: 'A name should always be specified!'
  5.   }
  6. }
復(fù)制代碼


標(biāo)準(zhǔn)特性


總是優(yōu)先考慮使用標(biāo)準(zhǔn)特性。為了最大限度地保證擴(kuò)展性與兼容性,總是首選標(biāo)準(zhǔn)的特性,而不是非標(biāo)準(zhǔn)的特性(例如:首選string.charAt(3) 而不是 string[3];首選 DOM 的操作方法來(lái)獲得元素引用,而不是某一應(yīng)用特定的快捷方法)。


簡(jiǎn)易的原型繼承


如果你想在 JavaScript 中繼承你的對(duì)象,請(qǐng)遵循一個(gè)簡(jiǎn)易的模式來(lái)創(chuàng)建此繼承。如果你預(yù)計(jì)你會(huì)遇上復(fù)雜對(duì)象的繼承,那可以考慮采用一個(gè)繼承庫(kù),比如 Proto.js by Axel Rauschmayer.


簡(jiǎn)易繼承請(qǐng)用以下方式:


  1. (function(log){
  2.   'use strict';

  3.   // Constructor function
  4.   function Apple(name) {
  5.     this.name = name;
  6.   }
  7.   // Defining a method of apple
  8.   Apple.prototype.eat = function() {
  9.     log('Eating ' + this.name);
  10.   };

  11.   // Constructor function
  12.   function GrannySmithApple() {
  13.     // Invoking parent constructor
  14.     Apple.prototype.constructor.call(this, 'Granny Smith');
  15.   }
  16.   // Set parent prototype while creating a copy with Object.create
  17.   GrannySmithApple.prototype = Object.create(Apple.prototype);
  18.   // Set constructor to the sub type, otherwise points to Apple
  19.   GrannySmithApple.prototype.constructor = GrannySmithApple;

  20.   // Calling a super method
  21.   GrannySmithApple.prototype.eat = function() {
  22.     // Be sure to apply it onto our current object with call(this)
  23.     Apple.prototype.eat.call(this);

  24.     log('Poor Grany Smith');
  25.   };

  26.   // Instantiation
  27.   var apple = new Apple('Test Apple');
  28.   var grannyApple = new GrannySmithApple();

  29.   log(apple.name); // Test Apple
  30.   log(grannyApple.name); // Granny Smith

  31.   // Instance checks
  32.   log(apple instanceof Apple); // true
  33.   log(apple instanceof GrannySmithApple); // false

  34.   log(grannyApple instanceof Apple); // true
  35.   log(grannyApple instanceof GrannySmithApple); // true

  36.   // Calling method that calls super method
  37.   grannyApple.eat(); // Eating Granny Smith\nPoor Grany Smith

  38. }(window.console.log));
復(fù)制代碼


使用閉包


閉包的創(chuàng)建也許是 JS 最有用也是最易被忽略的能力了。關(guān)于閉包如何工作的合理解釋。


切勿在循環(huán)中創(chuàng)建函數(shù)


在簡(jiǎn)單的循環(huán)語(yǔ)句中加入函數(shù)是非常容易形成閉包而帶來(lái)隱患的。下面的例子就是一個(gè)典型的陷阱:


不推薦


  1. (function(log, w){
  2.   'use strict';

  3.   // numbers and i is defined in the current function closure
  4.   var numbers = [1, 2, 3],
  5.       i;

  6.   for(i = 0; i < numbers.length; i++) {
  7.     w.setTimeout(function() {
  8.       // At the moment when this gets executed the i variable, coming from the outer function scope
  9.       // is set to 3 and the current program is alerting the message 3 times
  10.       // 'Index 3 with number undefined
  11.       // If you understand closures in javascript you know how to deal with those cases
  12.       // It's best to just avoid functions / new closures in loops as this prevents those issues

  13.       w.alert('Index ' + i + ' with number ' + numbers[i]);
  14.     }, 0);
  15.   }

  16. }(window.console.log, window));
復(fù)制代碼


接下來(lái)的改進(jìn)雖然已經(jīng)解決了上述例子中的問(wèn)題或 bug,但還是違反了不在循環(huán)中創(chuàng)建函數(shù)或閉包的原則。


不推薦


  1. (function(log, w){
  2.   'use strict';

  3.   // numbers and i is defined in the current function closure
  4.   var numbers = [1, 2, 3],
  5.       i;

  6.   for(i = 0; i < numbers.length; i++) {
  7.     // Creating a new closure scope with an IIFE solves the problem
  8.     // The delayed function will use index and number which are
  9.     // in their own closure scope (one closure per loop iteration).
  10.     // ---
  11.     // Still this is not recommended as we violate our rule to not
  12.     // create functions within loops and we are creating two!

  13.     (function(index, number){
  14.       w.setTimeout(function() {
  15.         // Will output as expected 0 > 1, 1 > 2, 2 > 3
  16.         w.alert('Index ' + index + ' with number ' + number);
  17.       }, 0);
  18.     }(i, numbers[i]));
  19.   }

  20. }(window.console.log, window));
復(fù)制代碼


接下來(lái)的改進(jìn)已解決問(wèn)題,而且也遵循了規(guī)范。可是,你會(huì)發(fā)現(xiàn)看上去似乎過(guò)于復(fù)雜繁冗了,應(yīng)該會(huì)有更好的解決方案吧。


不完全推薦


  1. (function(log, w){
  2.   'use strict';

  3.   // numbers and i is defined in the current function closure
  4.   var numbers = [1, 2, 3],
  5.       i;

  6.   // Create a function outside of the loop that will accept arguments to create a
  7.   // function closure scope. This function will return a function that executes in this
  8.   // closure parent scope.
  9.   function alertIndexWithNumber(index, number) {
  10.     return function() {
  11.       w.alert('Index ' + index + ' with number ' + number);
  12.     };
  13.   }

  14.   // First parameter is a function call that returns a function.
  15.   // ---
  16.   // This solves our problem and we don't create a function inside our loop
  17.   for(i = 0; i < numbers.length; i++) {
  18.     w.setTimeout(alertIndexWithNumber(i, numbers[i]), 0);
  19.   }

  20. }(window.console.log, window));
復(fù)制代碼


將循環(huán)語(yǔ)句轉(zhuǎn)換為函數(shù)執(zhí)行的方式問(wèn)題能得到立馬解決,每一次循環(huán)都會(huì)對(duì)應(yīng)地創(chuàng)建一次閉包。函數(shù)式的風(fēng)格更加值得推薦,而且看上去也更加地自然和可預(yù)料。


推薦


  1. (function(log, w){
  2.   'use strict';

  3.   // numbers and i is defined in the current function closure
  4.   var numbers = [1, 2, 3],
  5.       i;

  6.   numbers.forEach(function(number, index) {
  7.     w.setTimeout(function() {
  8.       w.alert('Index ' + index + ' with number ' + number);
  9.     }, 0);
  10.   });

  11. }(window.console.log, window));
復(fù)制代碼


eval 函數(shù)(魔鬼)


eval() 不但混淆語(yǔ)境還很危險(xiǎn),總會(huì)有比這更好、更清晰、更安全的另一種方案來(lái)寫你的代碼,因此盡量不要使用 evil 函數(shù)。


this 關(guān)鍵字


只在對(duì)象構(gòu)造器、方法和在設(shè)定的閉包中使用 this 關(guān)鍵字。this 的語(yǔ)義在此有些誤導(dǎo)。它時(shí)而指向全局對(duì)象(大多數(shù)時(shí)),時(shí)而指向調(diào)用者的定義域(在 eval 中),時(shí)而指向 DOM 樹中的某一節(jié)點(diǎn)(當(dāng)用事件處理綁定到 HTML 屬性上時(shí)),時(shí)而指向一個(gè)新創(chuàng)建的對(duì)象(在構(gòu)造器中),還時(shí)而指向其它的一些對(duì)象(如果函數(shù)被 call() 和 apply() 執(zhí)行和調(diào)用時(shí))。


正因?yàn)樗侨绱巳菀椎乇桓沐e(cuò),請(qǐng)限制它的使用場(chǎng)景:


  • 在構(gòu)造函數(shù)中
  • 在對(duì)象的方法中(包括由此創(chuàng)建出的閉包內(nèi))

首選函數(shù)式風(fēng)格



函數(shù)式編程讓你可以簡(jiǎn)化代碼并縮減維護(hù)成本,因?yàn)樗菀讖?fù)用,又適當(dāng)?shù)亟怦詈透俚囊蕾嚒?/font>


接下來(lái)的例子中,在一組數(shù)字求和的同一問(wèn)題上,比較了兩種解決方案。第一個(gè)例子是經(jīng)典的程序處理,而第二個(gè)例子則是采用了函數(shù)式編程和 ECMA Script 5.1 的數(shù)組方法。


例外:往往在重代碼性能輕代碼維護(hù)的情況之下,要選擇最優(yōu)性能的解決方案而非維護(hù)性高的方案(比如用簡(jiǎn)單的循環(huán)語(yǔ)句代替 forEach)。


不推薦


  1. (function(log){
  2.   'use strict';

  3.   var arr = [10, 3, 7, 9, 100, 20],
  4.       sum = 0,
  5.       i;


  6.   for(i = 0; i < arr.length; i++) {
  7.     sum += arr[i];
  8.   }

  9.   log('The sum of array ' + arr + ' is: ' + sum)

  10. }(window.console.log));
復(fù)制代碼


推薦


  1. (function(log){
  2.   'use strict';

  3.   var arr = [10, 3, 7, 9, 100, 20];

  4.   var sum = arr.reduce(function(prevValue, currentValue) {
  5.     return prevValue + currentValue;
  6.   }, 0);

  7.   log('The sum of array ' + arr + ' is: ' + sum);

  8. }(window.console.log));
復(fù)制代碼


另一個(gè)例子通過(guò)某一規(guī)則對(duì)一個(gè)數(shù)組進(jìn)行過(guò)濾匹配來(lái)創(chuàng)建一個(gè)新的數(shù)組。


不推薦


  1. (function(log){
  2.   'use strict';

  3.   var numbers = [11, 3, 7, 9, 100, 20, 14, 10],
  4.       numbersGreaterTen = [],
  5.       i;


  6.   for(i = 0; i < numbers.length; i++) {
  7.     if(numbers[i] > 10) {
  8.       numbersGreaterTen.push(numbers[i]);
  9.     }
  10.   }

  11.   log('From the list of numbers ' + numbers + ' only ' + numbersGreaterTen + ' are greater than ten');

  12. }(window.console.log));
復(fù)制代碼


推薦


  1. (function(log){
  2.   'use strict';

  3.   var numbers = [11, 3, 7, 9, 100, 20, 14, 10];

  4.   var numbersGreaterTen = numbers.filter(function(element) {
  5.     return element > 10;
  6.   });

  7.   log('From the list of numbers ' + numbers + ' only ' + numbersGreaterTen + ' are greater than ten');

  8. }(window.console.log));
復(fù)制代碼


使用 ECMA Script 5


建議使用 ECMA Script 5 中新增的語(yǔ)法糖和函數(shù)。這將簡(jiǎn)化你的程序,并讓你的代碼更加靈活和可復(fù)用。


數(shù)組和對(duì)象的屬性迭代


用 ECMA5 的迭代方法來(lái)迭代數(shù)組。使用 Array.forEach 或者如果你要在特殊場(chǎng)合下中斷迭代,那就用 Array.every。


  1. (function(log){
  2.   'use strict';

  3.   // Iterate over an array and break at a certain condition
  4.   [1, 2, 3, 4, 5].every(function(element, index, arr) {
  5.     log(element + ' at index ' + index + ' in array ' + arr);

  6.     if(index !== 5) {
  7.       return true;
  8.     }
  9.   });

  10.   // Defining a simple javascript object
  11.   var obj = {
  12.     a: 'A',
  13.     b: 'B',
  14.     'c-d-e': 'CDE'
  15.   };

  16.   // Iterating over the object keys
  17.   Object.keys(obj).forEach(function(element, index, arr) {
  18.     log('Key ' + element + ' has value ' + obj[element]);
  19.   });

  20. }(window.console.log));
復(fù)制代碼


不要使用 switch


switch 在所有的編程語(yǔ)言中都是個(gè)非常錯(cuò)誤的難以控制的語(yǔ)句,建議用 if else 來(lái)替換它。


這個(gè)我表示不同意


數(shù)組和對(duì)象字面量


用數(shù)組和對(duì)象字面量來(lái)代替數(shù)組和對(duì)象構(gòu)造器。數(shù)組構(gòu)造器很容易讓人在它的參數(shù)上犯錯(cuò)。


不推薦


  1. // Length is 3.
  2. var a1 = new Array(x1, x2, x3);

  3. // Length is 2.
  4. var a2 = new Array(x1, x2);

  5. // If x1 is a number and it is a natural number the length will be x1.
  6. // If x1 is a number but not a natural number this will throw an exception.
  7. // Otherwise the array will have one element with x1 as its value.
  8. var a3 = new Array(x1);

  9. // Length is 0.
  10. var a4 = new Array();
復(fù)制代碼


正因如此,如果將代碼傳參從兩個(gè)變?yōu)橐粋€(gè),那數(shù)組很有可能發(fā)生意料不到的長(zhǎng)度變化。為避免此類怪異狀況,請(qǐng)總是采用更多可讀的數(shù)組字面量。


推薦


  1. var a = [x1, x2, x3];
  2. var a2 = [x1, x2];
  3. var a3 = [x1];
  4. var a4 = [];
復(fù)制代碼


對(duì)象構(gòu)造器不會(huì)有類似的問(wèn)題,但是為了可讀性和統(tǒng)一性,我們應(yīng)該使用對(duì)象字面量。


不推薦


  1. var o = new Object();

  2. var o2 = new Object();
  3. o2.a = 0;
  4. o2.b = 1;
  5. o2.c = 2;
  6. o2['strange key'] = 3;
復(fù)制代碼


應(yīng)該寫成這樣:


推薦


  1. var o = {};

  2. var o2 = {
  3.   a: 0,
  4.   b: 1,
  5.   c: 2,
  6.   'strange key': 3
  7. };
復(fù)制代碼


修改內(nèi)建對(duì)象的原型鏈


修改內(nèi)建的諸如 Object.prototype 和 Array.prototype 是被嚴(yán)厲禁止的。修改其它的內(nèi)建對(duì)象比如 Function.prototype,雖危害沒那么大,但始終還是會(huì)導(dǎo)致在開發(fā)過(guò)程中難以 debug 的問(wèn)題,應(yīng)當(dāng)也要避免。


自定義 toString() 方法


你可以通過(guò)自定義 toString() 來(lái)控制對(duì)象字符串化。這很好,但你必須保證你的方法總是成功并不會(huì)有其它副作用。如果你的方法達(dá)不到這樣的標(biāo)準(zhǔn),那將會(huì)引發(fā)嚴(yán)重的問(wèn)題。如果 toString() 調(diào)用了一個(gè)方法,這個(gè)方法做了一個(gè)斷言[3] ,當(dāng)斷言失敗,它可能會(huì)輸出它所在對(duì)象的名稱,當(dāng)然對(duì)象也需要調(diào)用 toString()。


圓括號(hào)


一般在語(yǔ)法和語(yǔ)義上真正需要時(shí)才謹(jǐn)慎地使用圓括號(hào)。不要用在一元操作符上,例如 delete, typeof 和 void,或在關(guān)鍵字之后,例如return, throw, case, new 等。


字符串


統(tǒng)一使用單引號(hào)(’),不使用雙引號(hào)(“)。這在創(chuàng)建 HTML 字符串非常有好處:


var msg = 'This is some HTML <div class="makes-sense"></div>';
三元條件判斷(if 的快捷方法)


用三元操作符分配或返回語(yǔ)句。在比較簡(jiǎn)單的情況下使用,避免在復(fù)雜的情況下使用。沒人愿意用 10 行三元操作符把自己的腦子繞暈。


不推薦


  1. if(x === 10) {
  2.   return 'valid';
  3. } else {
  4.   return 'invalid';
  5. }
復(fù)制代碼


推薦


  1. return x === 10 ? 'valid' : 'invalid';
復(fù)制代碼


[1]:作者指的是采用嚴(yán)格規(guī)范的語(yǔ)句寫法,從根本上杜絕由分號(hào)缺失而引起的代碼歧義。


[2]:中綴符,指的是像 x + y 中的 +。


[3]:斷言一般指程序員在測(cè)試測(cè)序時(shí)的假設(shè),一般是一些布爾表達(dá)式,當(dāng)返回是 true 時(shí),斷言為真,代碼運(yùn)行會(huì)繼續(xù)進(jìn)行;如果條件判斷為 false,代碼運(yùn)行停止,你的應(yīng)用被終止。


via:http://www.cnblogs.com/afrog/archive/2015/01/16/4228103.html

【網(wǎng)站聲明】本站除付費(fèi)源碼經(jīng)過(guò)測(cè)試外,其他素材未做測(cè)試,不保證完整性,網(wǎng)站上部分源碼僅限學(xué)習(xí)交流,請(qǐng)勿用于商業(yè)用途。如損害你的權(quán)益請(qǐng)聯(lián)系客服QQ:2655101040 給予處理,謝謝支持。

相關(guān)文檔推薦

由于實(shí)際運(yùn)行環(huán)境是在瀏覽器中,因此性能還取決于JavaScript解釋器的效率,指定的FPS幀速在低性能解釋器中可能不會(huì)達(dá)到,所以這部分不是開發(fā)者能夠決定的,開發(fā)者能作的是盡可能通
本文將使用HTML5提供的VideoAPI做一個(gè)自定義的視頻播放器,需要用到HTML5提供的video標(biāo)簽、以及HTML5提供的對(duì)JavascriptAPI的擴(kuò)展。,HTML5中國(guó),中國(guó)最大的HTML5中文門戶。
隨著 Hybrid 應(yīng)用的豐富,HTML5 工程師們已經(jīng)不滿足于把桌面端體驗(yàn)簡(jiǎn)單移植到移動(dòng)端,他們覬覦移動(dòng)原生應(yīng)用人性化的操作體驗(yàn),特別是原生應(yīng)用與生俱來(lái)的豐富的手勢(shì)系統(tǒng)。HTML5 沒有提
你想要在自己網(wǎng)站上分享一個(gè)產(chǎn)品,或者是一個(gè)作品集,又或者僅僅只是一個(gè)靈感。在你發(fā)布到網(wǎng)上之前,你想讓它看起來(lái)有吸引力,專業(yè),或者至少得看起來(lái)像那么回事。那么你接下
H5廣告,包括H5廣告的設(shè)計(jì)流程,究竟有什么講究,和階段。為了能幫助更多的人了解H5廣告,我專門做了一個(gè)講義。同時(shí),也讓我意外的收到了非常好反饋和認(rèn)!這是對(duì)我的極大鼓勵(lì)!我的
本文主要內(nèi)容有:框架與組件、構(gòu)建生態(tài)、開發(fā)技巧與調(diào)試、html、css與重構(gòu)、native/hybrid/桌面開發(fā)、前端/H5優(yōu)化、全棧/全端開發(fā)、研究實(shí)驗(yàn)、數(shù)據(jù)分析與監(jiān)控、其它軟技能、前端技術(shù)網(wǎng)
主站蜘蛛池模板: 日本伊人网 | 视频一区二区在线观看 | www.日韩av| 九九色影院 | 午夜xxx| 免费在线小视频 | av网站在线免费观看 | 伊人免费视频 | 人人干人人澡 | 中文字幕亚洲欧美 | 日韩视频一区 | 91日韩在线| 黄视频网站在线观看 | 一级特黄妇女高潮 | 三级在线播放 | 成人免费视频视频 | 日韩在线观看一区 | 中文字幕一区二区三区视频 | 成人爽a毛片一区二区免费 www.欧美精品 | 天天爱夜夜操 | 免费黄视频网站 | 日韩理论在线观看 | 国产成人av网站 | 日本一本草久p | 欧美综合久久 | 日韩精品国产精品 | 天天摸天天操 | 日韩精品视频网站 | 亚洲成人中文字幕 | 日韩一区在线视频 | 国产精品久久久久久久久久久久午夜片 | 久久精品欧美一区二区三区不卡 | 欧美在线不卡 | 欧美日韩三级 | 美女一级毛片 | 久久久久久一区二区 | 成人在线一区二区 | 欧美高清在线 | 小sao货撅起屁股扒开c微博 | 日韩伦理一区 | 国产福利视频在线 |