最近在看前端大牛Nicbolas C.Zakas的《编写可维护的JavaScript代码》一书。觉得里面的很多知识点都写的很好,所以,就写篇博文,总结一下吧!编码规范对于程序设计来说是很重要的,因为如果编码风格不一致的话,代码看上去就会很乱,是很难维护的。当然,不同的开发团队有着不同的编码规范,比较著名的有,Google编码规范,jQuery编码规范,dojo编码规范以及Yahoo!编码规范,等等。
// 推荐写法,在运算符结尾处断行(逗号也是运算符),而且缩进也正确,用了二级缩进 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
原文:http://www.cnblogs.com/yugege/p/4979137.html