最近在看前端大牛Nicbolas C.Zakas的《編寫可維護的JavaScript代碼》一書。以爲裏面的不少知識點都寫的很好,因此,就寫篇博文,總結一下吧!編碼規範對於程序設計來講是很重要的,由於若是編碼風格不一致的話,代碼看上去就會很亂,是很難維護的。固然,不一樣的開發團隊有着不一樣的編碼規範,比較著名的有,Google編碼規範,jQuery編碼規範,dojo編碼規範以及Yahoo!編碼規範,等等。 javascript
// 推薦寫法,在運算符結尾處斷行(逗號也是運算符),並且縮進也正確,用了二級縮進 callAFunction(document, element, window, "some string value", true, 123, navigator); // 不推薦寫法,由於只用了一級縮進 callAFunction(document, element, window, "some string value", true, 123, navigator); // Bad: 不推薦寫法,不是以運算符結尾處斷行 callAFunction(document, element, window, "some string value", true, 123 , navigator);
if (isLeapYear && isFebruary && day == 29 && itsYourBirthday && noPlans) { waitAnotherFourYears(); }
var result = something + anotherThing + yetAnotherThing + somethingElse + anotherSomethingElse;
var schoolName;
var schoolName;
function getSchoolName() { }
// 推薦寫法 function Person(name) { this.name = name; } Person.prototype.sayName = function() { alert(this.name); }; var me = new Person("Nicholas");
var name = "Nicholas says, \"Hi.\""; var name = 'Nicholas says, "Hi"';
var p1, p2; p1 = "Tom"; p2 = "Jane"
//不推薦寫法 var longString = "Here's the story, of a man \ named Brady."; //推薦寫法 var longString = "Here's the story, of a man " + "named Brady.";
if (condition) doSomething();
if (condition) doSomething(); doSomethingElse();
if (condition) { doSomething(); }
if (condition) { doSomething(); } else { doSomethingElse(); }
if (condition) { doSomething(); } else { doSomethingElse(); }
if (condition) { doSomething(); }
// 推薦寫法 doSomething(item);
// 不推薦寫法,這看起來像塊級語句了 doSomething (item);
// The number 5 and string 5 console.log(5 == "5"); // true // The number 25 and hexadecimal string 25 console.log(25 == "0x19"); // true