Javascript程序应该尽量放在.js的文件中,需要调用的时候在页面中以<script src="filename.js">的形式包含进来。Javascript代码若不是该页面专用的,则应尽量避免在页面中直接编写Javascript代码。
在以下位置必须换行:
每个独立语句结束后;if、else、catch、finally、while等关键字前;运算符处换行时,运算符必须在新行的行首。 对于因为单行长度超过限制时产生的换行,参考行长度中的策略进行分隔。 字符串过长截断每行代码应小于80个字符。若代码较长应尽量换行,换行应选择在操作符和标点符号之后,最好是在分号“;”或逗号“,”之后。下一行代码相对上一行缩进4个空格。这样可以有效防止复制粘贴引起的代码缺失等错误并增强可读性。
三元运算符过长 三元运算符由3部分组成,因此其换行应当根据每个部分的长度不同,形成3种不同的情况: <script> // 无需换行 var result = condition ? resultA : resultB; // 条件超长的情况 var result = thisIsAVeryVeryLongCondition ? resultA : resultB; // 结果分支超长的情况 var result = condition ? thisIsAVeryVeryLongCondition :resultB; var result = condition ? resultA : thisIsAVeryVeryLongCondition; </script> 不得出现以下情况: <script> // 最后一个结果很长,但不建议合并条件和第一个分支 // 不要这么干 var result = condition ? resultA : thisIsAVeryVeryLongCondition; </script> 过长的逻辑条件组合 当因为较复杂的逻辑条件组合导致80个字符无法满足需求时,应当将每个条件独立一行,逻辑运算符放置在行首进行分隔,或将部分逻辑按逻辑组合进行分隔。最终将右括号)与左大括号{放在独立一行,保证与if内语句块能容易视觉辨识。如: <script> // 注意逻辑运算符前的缩进 if (user.isAuthenticated() && user.isInRole('admin') && user.hasAuthority('add-admin') || user.hasAuthority('delete-admin') ) { // code } </script> 过长的JSON和数组 如果对象属性较多导致每个属性一行占用空间过大,可以按语义或逻辑进行分组的组织,如: <script> // 引文-数字的映射 var mapping = { one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight:8, nine: 9, ten: 10, eleven: 11 } </script> 通过5个一组的分组,将每一行控制在合理的范围内,并且按逻辑进行了切分。 对于项目较多的数组,也可以采用相同的方法 eturn语句 return如果用表达式的执行作为返回值,请把表达式和 return 放在同一行中,以免换行符被误解析为语句的结束而引起返回错误。return 关键字后若没有返回表达式,则返回 undefined。构造器的默认返回值为 this。命名的方法通常有以下几类: 1. 命名法说明 - 1).camel命名法,形如thisIsAnApple - 2).pascal命名法,形如ThisIsAnApple - 3).下划线命名法,形如this_is_an_apple · - 4).中划线命名法,形如this-is-an-apple 根据不同类型的内容,必须严格采用如下的命名法:
变量名:必须使用camel命名法参数名:必须使用camel命名法 函数名:必须使用camel命名法方法/属性:必须使用camel命名法私有(保护)成员:必须以下划线_开头常量名:必须使用全部大写的下划线命名法,如IS_DEBUG_ENABLED类名:必须使用pascal命名法枚举名:必须使用pascal命名法 枚举的属性:必须使用全部大写的下划线命名法命名空间:必须使用camel命名法 语义:命名同时还需要关注语义,如: 变量名应当使用名词; boolean类型的应当使用is、has等起头,表示其类型;· 函数名应当用动宾短语;类名应当用名词。变量的声明
尽管 JavaScript 语言并不要求在变量使用前先对变量进行声明。但我们还是应该养成这个好习惯。这样可以比较容易的检测出那些未经声明的变量,避免其变为隐藏的全局变量,造成隐患。
在函数的开始应先用 var 关键字声明函数中要使用的局部变量,注释变量的功能及代表的含义,且应以字母顺序排序。每个变量单独占一行,以便添加注释。这是因为 JavaScript 中只有函数的 {} 表明作用域,用 var 关键字声明的局部变量只在函数内有效,而未经 var 声明的变量则被视为全局变量。示例:
<script> var valueA = "a"; var valueB = "b"; function f1() { var valueA = "c"; alert("valueA=" + valueA); // output: valueA=c valueB = "d"; alert("valueB=" + valueB); // output: valueB=d } f1(); alert("valueA=" + valueA); // output: valueA=a alert("valueB=" + valueB); // output: valueB=d </script> 用 var 声明过的变量 valueA 和没有声明的变量 valueB 是有区别的。特别需要注意的是,在函数内部用 var 声明的变量为局部变量,这样可以有效地避免因局部变量和全局变量同名而产生的错误。注释要尽量简单,清晰明了。着重注释的意思,对不太直观的部分进行注解
JavaScript 的注释有两种”//” 和”/* …. */” - 建议”//”用作代码行注释 - “/* …. */”形式用作对整个代码段的注销,或较正式的声明中,如函数参数、功能、文件功能等的描述中 - >另:复制粘贴应注意注释是否与代码对应。
使用 /* … / 进行多行注释,包括描述,指定类型以及参数值和返回值 <script> // bad // make() returns a new element // based on the passed in tag name // // @param <String> tag // @return <Element> element function 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; } </script> 使用 // 进行单行注释,在评论对象的上面进行单行注释,注释前放一个空行. <script> // bad var active = true; // is current tab // good // is current tab var active = true; // bad function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type; } // good function getType() { console.log('fetching type...'); // set the default type to 'no type' var type = this._type || 'no type'; return type; } </script> 如果你有一个问题需要重新来看一下或如果你建议一个需要被实现的解决方法的话需要在你的注释前面加上 FIXME 或 TODO 帮助其他人迅速理解 <script> 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; } </script>将tab设为4个空格
// bad function() { ∙∙var name; } // bad function() { ∙var name; } // good function() { ∙∙∙∙var name; }大括号前放一个空格
// bad function test(){ console.log('test'); } // good function test() { console.log('test'); } // bad dog.set('attr',{ age: '1 year', breed: 'Bernese Mountain Dog' }); // good dog.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(); // bad var 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); // good var 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);不要将逗号放前面
// bad var once , upon , aTime; // good var once, upon, aTime; // bad var hero = { firstName: 'Bob' , lastName: 'Parr' , heroName: 'Mr. Incredible' , superPower: 'strength' }; // good var hero = { firstName: 'Bob', lastName: 'Parr', heroName: 'Mr. Incredible', superPower: 'strength' };不要加多余的逗号,这可能会在IE下引起错误,同时如果多一个逗号某些ES3的实现会计算多数组的长度。
// bad var hero = { firstName: 'Kevin', lastName: 'Flynn', }; var heroes = [ 'Batman', 'Superman', ]; // good var hero = { firstName: 'Kevin', lastName: 'Flynn' }; var heroes = [ 'Batman', 'Superman' ];语句结束一定要加分号
// bad (function() { var name = 'Skywalker' return name })() // good (function() { var name = 'Skywalker'; return name; })(); // good ;(function() { var name = 'Skywalker'; return name; })();字符串:
// => this.reviewScore = 9; // bad var totalScore = this.reviewScore + ''; // good var totalScore = '' + this.reviewScore; // bad var totalScore = '' + this.reviewScore + ' total score'; // good var totalScore = this.reviewScore + ' total score';对数字使用 parseInt 并且总是带上类型转换的基数.
var inputValue = '4'; // bad var val = new Number(inputValue); // bad var val = +inputValue; // bad var val = inputValue >> 0; // bad var val = parseInt(inputValue); // good var val = Number(inputValue); // good var 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; // bad var hasAge = new Boolean(age); // good var hasAge = Boolean(age); // good var hasAge = !!age;避免单个字符名,让你的变量名有描述意义。
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. }当命名对象、函数和实例时使用驼峰命名规则
// bad var OBJEcttsssss = {}; var this_is_my_object = {}; var this-is-my-object = {}; function c() {}; var u = new user({ name: 'Bob Parr' }); // good var thisIsMyObject = {}; function thisIsMyFunction() {}; var user = new User({ name: 'Bob Parr' });当命名构造函数或类时使用驼峰式大写
// bad function user(options) { this.name = options.name; } var bad = new user({ name: 'nope' }); // good function User(options) { this.name = options.name; } var good = new User({ name: 'yup' });命名私有属性时前面加个下划线 _
// bad this.__firstName__ = 'Panda'; this.firstName_ = 'Panda'; // good this._firstName = 'Panda';当保存对 this 的引用时使用 _this.
// bad function() { var self = this; return function() { console.log(self); }; } // bad function() { var that = this; return function() { console.log(that); }; } // good function() { var _this = this; return function() { console.log(_this); }; }如果你确实有存取器函数的话使用getVal() 和 setVal(‘hello’)
// bad dragon.age(); // good dragon.getAge(); // bad dragon.age(25); // good dragon.setAge(25);如果属性是布尔值,使用isVal() 或 hasVal()
// bad if (!dragon.age()) { return false; } // good if (!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'); } // bad Jedi.prototype = { fight: function fight() { console.log('fighting'); }, block: function block() { console.log('blocking'); } }; // good Jedi.prototype.fight = function fight() { console.log('fighting'); }; Jedi.prototype.block = function block() { console.log('blocking'); };方法可以返回 this 帮助方法可链。
// bad Jedi.prototype.jump = function() { this.jumping = true; return true; }; Jedi.prototype.setHeight = function(height) { this.height = height; }; var luke = new Jedi(); luke.jump(); // => true luke.setHeight(20) // => undefined // good Jedi.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 });总是在模块顶部声明 'use strict';
// fancyInput/fancyInput.js !function(global) { 'use strict'; var previousFancyInput = global.FancyInput; function FancyInput(options) { this.options = options || {}; } FancyInput.noConflict = function noConflict() { global.FancyInput = previousFancyInput; return FancyInput; }; global.FancyInput = FancyInput; }(this);缓存jQuery查询
// bad function setSidebar() { $('.sidebar').hide(); // ...stuff... $('.sidebar').css({ 'background-color': 'pink' }); } // good function 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');