[譯]JavaScript規範-葵花寶典,javascript葵花寶典
【譯】JavaScript規範
譯自:https://github.com/airbnb/javascript
類型
stringnumberbooleannullundefinedvar foo = 1, bar = foo;bar = 9;console.log(foo, bar); // => 1, 9
複雜類型: 相當於傳引用
-
objectarrayfunctionvar foo = [1, 2], bar = foo;bar[0] = 9;console.log(foo[0], bar[0]); // => 9, 9
對象
-
使用字面值建立對象
// badvar item = new Object();// goodvar item = {};
-
不要使用保留字 reserved words 作為鍵
// badvar superman = { class: 'superhero', default: { clark: 'kent' }, private: true};// goodvar superman = { klass: 'superhero', defaults: { clark: 'kent' }, hidden: true};
數組
-
使用字面值建立數組
// badvar items = new Array();// goodvar items = [];
-
如果你不知道數組的長度,使用push
var someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');
-
當你需要拷貝數組時使用slice. jsPerf
var len = items.length, itemsCopy = [], i;// badfor (i = 0; i < len; i++) { itemsCopy[i] = items[i];}// gooditemsCopy = items.slice();
-
使用slice將類數組的對象轉成數組.
function trigger() { var args = Array.prototype.slice.call(arguments); ...}
字串
-
對字串使用單引號 ''
// badvar name = "Bob Parr";// goodvar name = 'Bob Parr';// badvar fullName = "Bob " + this.lastName;// goodvar fullName = 'Bob ' + this.lastName;
-
超過80個字元的字串應該使用字串串連換行
-
注: 如果過度使用,長字串串連可能會對效能有影響. jsPerf & Discussion
// badvar errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.';// badvar errorMessage = 'This is a super long error that \was thrown because of Batman. \When you stop to think about \how Batman had anything to do \with this, you would get nowhere \fast.';// goodvar errorMessage = 'This is a super long error that ' + 'was thrown because of Batman.' + 'When you stop to think about ' + 'how Batman had anything to do ' + 'with this, you would get nowhere ' + 'fast.';
-
編程時使用join而不是字串串連來構建字串,特別是IE: jsPerf.
var items, messages, length, i;messages = [{ state: 'success', message: 'This one worked.'},{ state: 'success', message: 'This one worked as well.'},{ state: 'error', message: 'This one did not work.'}];length = messages.length;// badfunction inbox(messages) { items = '<ul>'; for (i = 0; i < length; i++) { items += '<li>' + messages[i].message + '</li>'; } return items + '</ul>';}// goodfunction inbox(messages) { items = []; for (i = 0; i < length; i++) { items[i] = messages[i].message; } return '<ul><li>' + items.join('</li><li>') + '</li></ul>';}
<函數
-
函數運算式:
// 匿名函數運算式var anonymous = function() { return true;};// 有名函數運算式var named = function named() { return true;};// 立即調用函數運算式(function() { console.log('Welcome to the Internet. Please follow me.');})();
-
絕對不要在一個非函數塊裡聲明一個函數,把那個函數賦給一個變數。瀏覽器允許你這麼做,但是它們解析不同。
-
注: ECMA-262定義把塊定義為一組語句,函式宣告不是一個語句。閱讀ECMA-262對這個問題的說明.
// badif (currentUser) { function test() { console.log('Nope.'); }}// goodif (currentUser) { var test = function test() { console.log('Yup.'); };}
-
絕對不要把參數命名為 arguments, 這將會逾越函數範圍內傳過來的 arguments 對象.
// badfunction nope(name, options, arguments) { // ...stuff...}// goodfunction yup(name, options, args) { // ...stuff...}
屬性
變數
-
總是使用 var 來聲明變數,如果不這麼做將導致產生全域變數,我們要避免汙染全域命名空間。
// badsuperPower = new SuperPower();// goodvar superPower = new SuperPower();
-
使用一個 var 以及新行聲明多個變數,縮排4個空格。
// badvar items = getItems();var goSportsTeam = true;var dragonball = 'z';// goodvar items = getItems(), goSportsTeam = true, dragonball = 'z';
-
最後再聲明未賦值的變數,當你想引用之前已賦值變數的時候很有用。
// badvar i, len, dragonball, items = getItems(), goSportsTeam = true;// badvar i, items = getItems(), dragonball, goSportsTeam = true, len;// goodvar items = getItems(), goSportsTeam = true, dragonball, length, i;
-
在範圍頂部聲明變數,避免變數聲明和賦值引起的相關問題。
// badfunction() { test(); console.log('doing stuff..'); //..other stuff.. var name = getName(); if (name === 'test') { return false; } return name;}// goodfunction() { var name = getName(); test(); console.log('doing stuff..'); //..other stuff.. if (name === 'test') { return false; } return name;}// badfunction() { var name = getName(); if (!arguments.length) { return false; } return true;}// goodfunction() { if (!arguments.length) { return false; } var name = getName(); return true;}
條件運算式和等號
- 適當使用
=== 和 !== 以及 == 和 !=.
-
條件運算式的強制類型轉換遵循以下規則:
- 對象 被計算為 true
- Undefined 被計算為 false
- Null 被計算為 false
- 布爾值 被計算為 布爾的值
- 數字 如果是 +0, -0, or NaN 被計算為 false , 否則為 true
- 字串 如果是Null 字元串
'' 則被計算為 false, 否則為 true
if ([0]) { // true // An array is an object, objects evaluate to true}
-
使用捷徑.
// badif (name !== '') { // ...stuff...}// goodif (name) { // ...stuff...}// badif (collection.length > 0) { // ...stuff...}// goodif (collection.length) { // ...stuff...}
-
閱讀 Truth Equality and JavaScript 瞭解更多
塊
注釋
-
使用 /** ... */ 進行多行注釋,包括描述,指定類型以及參數值和傳回值
// bad// make() returns a new element// based on the passed in tag name//// @param <String> tag// @return <Element> elementfunction make(tag) { // ...stuff... return element;}// good/** * make() returns a new element * based on the passed in tag name * * @param <String> tag * @return <Element> element */function make(tag) { // ...stuff... return element;}
-
使用 // 進行單行注釋,在評論對象的上面進行單行注釋,注釋前放一個空行.
// badvar active = true; // is current tab// good// is current tabvar active = true;// badfunction getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type;}// goodfunction getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type;}
-
如果你有一個問題需要重新來看一下或如果你建議一個需要被實現的解決方案的話需要在你的注釋前面加上 FIXME 或 TODO 協助其他人迅速理解
function Calculator() { // FIXME: shouldn't use a global here total = 0; return this;}function Calculator() { // TODO: total should be configurable by an options param this.total = 0; return this;}
空白
-
將tab設為4個空格
// badfunction() {∙∙var name;}// badfunction() {∙var name;}// goodfunction() {∙∙∙∙var name;}
-
大括弧前放一個空格
// badfunction test(){ console.log('test');}// goodfunction test() { console.log('test');}// baddog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog'});// gooddog.set('attr', { age: '1 year', breed: 'Bernese Mountain Dog'});
-
在做長方法鏈時使用縮排.
// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// good$('#items') .find('.selected') .highlight() .end() .find('.open') .updateCount();// badvar leds = stage.selectAll('.led').data(data).enter().append('svg:svg').class('led', true) .attr('width', (radius + margin) * 2).append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led);// goodvar leds = stage.selectAll('.led') .data(data) .enter().append('svg:svg') .class('led', true) .attr('width', (radius + margin) * 2) .append('svg:g') .attr('transform', 'translate(' + (radius + margin) + ',' + (radius + margin) + ')') .call(tron.led);
逗號
-
不要將逗號放前面
// badvar once , upon , aTime;// goodvar once, upon, aTime;// badvar hero = { firstName: 'Bob' , lastName: 'Parr' , heroName: 'Mr. Incredible' , superPower: 'strength'};// goodvar hero = { firstName: 'Bob', lastName: 'Parr', heroName: 'Mr. Incredible', superPower: 'strength'};
-
不要加多餘的逗號,這可能會在IE下引起錯誤,同時如果多一個逗號某些ES3的實現會計算多數組的長度。
// badvar hero = { firstName: 'Kevin', lastName: 'Flynn',};var heroes = [ 'Batman', 'Superman',];// goodvar hero = { firstName: 'Kevin', lastName: 'Flynn'};var heroes = [ 'Batman', 'Superman'];
分號
類型轉換
- 在語句的開始執行類型轉換.
-
字串:
// => this.reviewScore = 9;// badvar totalScore = this.reviewScore + '';// goodvar totalScore = '' + this.reviewScore;// badvar totalScore = '' + this.reviewScore + ' total score';// goodvar totalScore = this.reviewScore + ' total score';
-
對數字使用 parseInt 並且總是帶上類型轉換的基數.
var inputValue = '4';// badvar val = new Number(inputValue);// badvar val = +inputValue;// badvar val = inputValue >> 0;// badvar val = parseInt(inputValue);// goodvar val = Number(inputValue);// goodvar val = parseInt(inputValue, 10);// good/** * parseInt was the reason my code was slow. * Bitshifting the String to coerce it to a * Number made it a lot faster. */var val = inputValue >> 0;
-
布爾值:
var age = 0;// badvar hasAge = new Boolean(age);// goodvar hasAge = Boolean(age);// goodvar hasAge = !!age;
命名規範
-
避免單個字元名,讓你的變數名有描述意義。
// badfunction q() { // ...stuff...}// goodfunction query() { // ..stuff..}
-
當命名物件、函數和執行個體時使用駝峰命名規則
// badvar OBJEcttsssss = {};var this_is_my_object = {};var this-is-my-object = {};function c() {};var u = new user({ name: 'Bob Parr'});// goodvar thisIsMyObject = {};function thisIsMyFunction() {};var user = new User({ name: 'Bob Parr'});
-
當命名建構函式或類時使用駝峰式大寫
// badfunction user(options) { this.name = options.name;}var bad = new user({ name: 'nope'});// goodfunction User(options) { this.name = options.name;}var good = new User({ name: 'yup'});
-
命名私人屬性時前面加個底線 _
// badthis.__firstName__ = 'Panda';this.firstName_ = 'Panda';// goodthis._firstName = 'Panda';
-
當儲存對 this 的引用時使用 _this.
// badfunction() { var self = this; return function() { console.log(self); };}// badfunction() { var that = this; return function() { console.log(that); };}// goodfunction() { var _this = this; return function() { console.log(_this); };}
存取器
- 屬性的存取器函數不是必需的
-
如果你確實有存取器函數的話使用getVal() 和 setVal('hello')
// baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25);
-
如果屬性是布爾值,使用isVal() 或 hasVal()
// badif (!dragon.age()) { return false;}// goodif (!dragon.hasAge()) { return false;}
-
可以建立get()和set()函數,但是要保持一致
function Jedi(options) { options || (options = {}); var lightsaber = options.lightsaber || 'blue'; this.set('lightsaber', lightsaber);}Jedi.prototype.set = function(key, val) { this[key] = val;};Jedi.prototype.get = function(key) { return this[key];};
構造器
-
給對象原型分配方法,而不是用一個新的對象覆蓋原型,覆蓋原型會使繼承出現問題。
function Jedi() { console.log('new jedi');}// badJedi.prototype = { fight: function fight() { console.log('fighting'); }, block: function block() { console.log('blocking'); }};// goodJedi.prototype.fight = function fight() { console.log('fighting');};Jedi.prototype.block = function block() { console.log('blocking');};
-
方法可以返回 this 協助方法可鏈。
// badJedi.prototype.jump = function() { this.jumping = true; return true;};Jedi.prototype.setHeight = function(height) { this.height = height;};var luke = new Jedi();luke.jump(); // => trueluke.setHeight(20) // => undefined// goodJedi.prototype.jump = function() { this.jumping = true; return this;};Jedi.prototype.setHeight = function(height) { this.height = height; return this;};var luke = new Jedi();luke.jump() .setHeight(20);
-
可以寫一個自訂的toString()方法,但是確保它工作正常並且不會有副作用。
function Jedi(options) { options || (options = {}); this.name = options.name || 'no name';}Jedi.prototype.getName = function getName() { return this.name;};Jedi.prototype.toString = function toString() { return 'Jedi - ' + this.getName();};
事件
-
當給事件附加資料時,傳入一個雜湊而不是原始值,這可以讓後面的貢獻者加入更多資料到事件數目據裡而不用找出並更新那個事件的事件處理器
// bad$(this).trigger('listingUpdated', listing.id);...$(this).on('listingUpdated', function(e, listingId) { // do something with listingId});
更好:
// good$(this).trigger('listingUpdated', { listingId : listing.id });...$(this).on('listingUpdated', function(e, data) { // do something with data.listingId});
模組
jQuery
-
緩衝jQuery查詢
// badfunction setSidebar() { $('.sidebar').hide(); // ...stuff... $('.sidebar').css({ 'background-color': 'pink' });}// goodfunction setSidebar() { var $sidebar = $('.sidebar'); $sidebar.hide(); // ...stuff... $sidebar.css({ 'background-color': 'pink' });}
-
對DOM查詢使用級聯的 $('.sidebar ul') 或 $('.sidebar ul'),jsPerf
-
對有範圍的jQuery物件查詢使用 find
// bad$('.sidebar', 'ul').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good (slower)$sidebar.find('ul');// good (faster)$($sidebar[0]).find('ul');
ECMAScript 5相容性
效能
- On Layout & Web Performance
- String vs Array Concat
- Try/Catch Cost In a Loop
- Bang Function
- jQuery Find vs Context, Selector
- innerHTML vs textContent for script text
- Long String Concatenation
-
Loading...
資源
Read This
- Annotated ECMAScript 5.1
- JavaScript Style Guide
其它規範
- Google JavaScript Style Guide
- jQuery Core Style Guidelines
- Principles of Writing Consistent, Idiomatic JavaScript
其它風格
- Naming this in nested functions - Christian Johansen
- Conditional Callbacks
閱讀更多
- Understanding JavaScript Closures - Angus Croll
書籍
- JavaScript: The Good Parts - Douglas Crockford
- JavaScript Patterns - Stoyan Stefanov
- Pro JavaScript Design Patterns - Ross Harmes and Dustin Diaz
- High Performance Web Sites: Essential Knowledge for Front-End Engineers - Steve Souders
- Maintainable JavaScript - Nicholas C. Zakas
- JavaScript Web Applications - Alex MacCaw
- Pro JavaScript Techniques - John Resig
- Smashing Node.js: JavaScript Everywhere - Guillermo Rauch