function test() { ... }
錯誤書寫:javascript
function test() { ... }
二、調用函數時函數名和左括號以前沒有空格,聲明函數時函數名與參數之間沒有空格,匿名函數'function'與左括號之間沒有空格,其它狀況,其它語法元素和左括號之間有一個空格html
正確書寫:java
test(a, b); function test(a, b) { ... } Test.prototype.getName = function() { ... };
錯誤書寫:git
test (a, b); return(a+b); if(a === b) { ... } function test (a, b) { ... } Test.prototype.getName = function () { ... };
4、引號
Javascript中單引號和雙引號沒有什麼語義區別,BYVoid在《Node.js開發指南》中建議使用單引號,「由於JSON、XML都規定了必須是雙引號,這樣便於無轉義地直接引用」
github
一、變量、屬性命名使用小駝峯命名法網絡
正確命名:函數
var testName = 'test';
錯誤命名:this
var TestName = 'test'; var test_name = 'test';
二、確保每一個語句定義一個變量,不用逗號隔開
正確命名:google
var test; var temp;
錯誤命名:編碼
var test, temp;
三、避免使用全局變量,使用 "var" 定義變量,由於沒寫 "var" 隱式定義是全局變量,可能會和現有變量衝突,也不明白變量的做用域是什麼。若使用全局變量用大寫字母、單詞以"_"分割表示,好比 "TEST_NAME = 'test'"
四、常量也使用全大寫、單詞以 "_" 分割命名方法,好比 "TEST_URL = 'http://www.test.com/test'"
五、普通的函數命名使用小駝峯命名,可是類要用大駝峯命名法;規定函數名與參數以前無空格,參數表和大括號以前要有一個空格,並在同一行
正確書寫:
function Test() { this.name = 'test'; } function testFunction() { return 'test'; }
錯誤書寫:
function test_function() { return 'test'; } function test() { this.name = 'test'; }
6、等號
使用 '===' 而不是 '==',由於 '==' 包含隱式轉換,會出現預想不到的結果
var num1 = 1; var num2 = '1'; if (num1 == num2) { console.log('true'); } else { console.log('false'); }
以上代碼將輸出 'true',若把 '==' 改成 '===',輸出 'false'
7、區塊
建議老是使用大括號表示塊
建議書寫:
if (true) { console.log('true'); }
不建議書寫:
if (true) console.log('true');
8、對象定義
成員函數經過原型定義,屬性在構造函數內定義
正確書寫:
function Person(name) { this.name = name; this.friends = ['Tom', 'Jack', 'Mike']; } Person.prototype.output = function() { console.log(this.friends); };
錯誤書寫:
function Person(name) { this.name = name; this.output = function() { console.log(this.friends); }; } Person.prototype.friends = ['Tom', 'Jack', 'Mike'];
9、繼承
不推薦繼承,若須要繼承用成熟的類庫繼承
有什麼建議或者有什麼錯誤,歡迎指出!
一、http://www.ruanyifeng.com/blog/2012/04/javascript_programming_style.html
二、http://www.cnblogs.com/hustskyking/p/javascript-spec.html
三、http://alloyteam.github.io/JX/doc/specification/google-javascript.xml
四、《Node.js開發指南》