ES6规范大全
来源:互联网 发布:网络微营销 编辑:程序博客网 时间:2024/06/13 10:36
转于:http://bubkoo.com/2015/04/05/javascript-style-guide/?utm_source=tuicool
类型
原始类型:值传递
string
number
boolean
null
undefined
123456
const foo = 1;let bar = foo;bar = 9;console.log(foo, bar); // => 1, 9
复杂类型:引用传递
object
array
function
123456
const foo = [1, 2];const bar = foo;bar[0] = 9;console.log(foo[0], bar[0]); // => 9, 9
引用
为引用使用
const
关键字,而不是var
这样确保你不能修改引用类型,否则可能会导致一些 bug 或难以理解的代码。
1234567
// badvar a = 1;var b = 2;// goodconst a = 1;const b = 2;
如果你必须修改引用,使用
let
代替var
因为
let
是块作用域的,而var
是函数作用域。
1234567891011
// badvar count = 1;if (true) {count += 1;}// good, use the let.let count = 1;if (true) {count += 1;}
let
和const
都是块作用域的
1234567
// const and let only exist in the blocks they are defined in.{let a = 1;const b = 1;}console.log(a); // ReferenceErrorconsole.log(b); // ReferenceError
对象
- 使用对象字面量创建对象
12345
// badvar item = new Object();// goodvar item = {};
- 不要使用保留字(reserved words)作为键,否则在 IE8 下将出错,issue
12345678910111213
// badvar superman = {class: 'superhero',default: { clark: 'kent' },private: true};// goodvar superman = {klass: 'superhero',defaults: { clark: 'kent' },hidden: true};
- 使用易读的同义词代替保留字
1234567891011121314
// badconst superman = {class: 'alien'};// badconst superman = {klass: 'alien'};// goodconst superman = {type: 'alien'};
创建对象时使用计算的属性名,而不要在创建对象后使用对象的动态特性
这样可以在同一个位置定义对象的所有属性。
1234567891011121314151617
function getKey(k) {return `a key named ${k}`;}// badconst obj = {id: 5,name: 'San Francisco'};obj[getKey('enabled')] = true;// goodconst obj = {id: 5,name: 'San Francisco',[getKey('enabled')]: true};
- 使用定义对象方法的简短形式
1234567891011121314151617
// badconst atom = {value: 1,addValue: function (value) {return atom.value + value;}};// goodconst atom = {value: 1,addValue(value) {return atom.value + value;}};
使用定义对象属性的简短形式
书写起来更加简单,并且可以自描述。
1234567891011
const lukeSkywalker = 'Luke Skywalker';// badconst obj = {lukeSkywalker: lukeSkywalker};// goodconst obj = {lukeSkywalker};
将所有简写的属性写在对象定义的最顶部
这样可以更加方便地知道哪些属性使用了简短形式。
12345678910111213141516171819202122
const anakinSkywalker = 'Anakin Skywalker';const lukeSkywalker = 'Luke Skywalker';// badconst obj = {episodeOne: 1,twoJedisWalkIntoACantina: 2,lukeSkywalker,episodeThree: 3,mayTheFourth: 4,anakinSkywalker};// goodconst obj = {lukeSkywalker,anakinSkywalker,episodeOne: 1,twoJedisWalkIntoACantina: 2,episodeThree: 3,mayTheFourth: 4};
数组
- 使用字面量语法创建数组
12345
// badconst items = new Array();// goodconst items = [];
- 如果你不知道数组的长度,使用
push
12345678
const someStack = [];// badsomeStack[someStack.length] = 'abracadabra';// goodsomeStack.push('abracadabra');
- 使用
...
来拷贝数组
1234567891011
// badconst len = items.length;const itemsCopy = [];let i;for (i = 0; i < len; i++) {itemsCopy[i] = items[i];}// goodconst itemsCopy = [...items];
- 使用
Array.from
将类数组对象转换为数组
12
const foo = document.querySelectorAll('.foo');const nodes = Array.from(foo);
解构 Destructuring
访问或使用对象的多个属性时请使用对象的解构赋值
解构赋值避免了为这些属性创建临时变量或对象。
123456789101112131415161718
// badfunction getFullName(user) {const firstName = user.firstName;const lastName = user.lastName;return `${firstName} ${lastName}`;}// goodfunction getFullName(obj) {const { firstName, lastName } = obj;return `${firstName} ${lastName}`;}// bestfunction getFullName({ firstName, lastName }) {return `${firstName} ${lastName}`;}
- 使用数组解构赋值
12345678
const arr = [1, 2, 3, 4];// badconst first = arr[0];const second = arr[1];// goodconst [first, second] = arr;
函数有多个返回值时使用对象解构,而不是数组解构
这样你就可以随时添加新的返回值或任意改变返回值的顺序,而不会导致调用失败。
12345678910111213141516
function processInput(input) {// then a miracle occursreturn [left, right, top, bottom];}// the caller needs to think about the order of return dataconst [left, __, top] = processInput(input);// goodfunction processInput(input) {// then a miracle occursreturn { left, right, top, bottom };}// the caller selects only the data they needconst { left, right } = processInput(input);
字符串
- 使用单引号
''
1234567891011
// badvar name = "Bob Parr";// goodvar name = 'Bob Parr';// badvar fullName = "Bob " + this.lastName;// goodvar fullName = 'Bob ' + this.lastName;
- 超过80个字符的字符串应该使用字符串连接换行
- 注:如果过度使用长字符串连接可能会对性能有影响。jsPerf & Discussion
12345678910111213141516171819
// 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.';
编程构建字符串时,使用字符串模板而不是字符串连接
模板给你一个可读的字符串,简洁的语法与适当的换行和字符串插值特性。
1234567891011121314
// badfunction sayHi(name) {return 'How are you, ' + name + '?';}// badfunction sayHi(name) {return ['How are you, ', name, '?'].join();}// goodfunction sayHi(name) {return `How are you, ${name}?`;}
函数
使用函数声明而不是函数表达式
函数声明拥有函数名,在调用栈中更加容易识别。并且,函数声明会整体提升,而函数表达式只会提升变量本身。这条规则也可以这样描述,始终使用箭头函数来代替函数表达式。
1234567
// badconst foo = function () {};// goodfunction foo() {}
- 函数表达式
1234
// immediately-invoked function expression (IIFE)(() => {console.log('Welcome to the Internet. Please follow me.');})();
- 绝对不要在一个非函数块(if,while,等等)里声明一个函数,把那个函数赋给一个变量。浏览器允许你这么做,但是它们解析不同
- 注:ECMA-262 把
块
定义为一组语句,函数声明不是一个语句。阅读 ECMA-262 对这个问题的说明
12345678910111213
// badif (currentUser) {function test() {console.log('Nope.');}}// goodif (currentUser) {var test = function test() {console.log('Yup.');};}
- 绝对不要把参数命名为
arguments
, 这将会覆盖函数作用域内传过来的arguments
对象
123456789
// badfunction nope(name, options, arguments) {// ...stuff...}// goodfunction yup(name, options, args) {// ...stuff...}
永远不要使用
arguments
,使用...
操作符来代替...
操作符可以明确指定你需要哪些参数,并且得到的是一个真实的数组,而不是arguments
这样的类数组对象。
12345678910
// badfunction concatenateAll() {const args = Array.prototype.slice.call(arguments);return args.join('');}// goodfunction concatenateAll(...args) {return args.join('');}
- 使用函数参数默认值语法,而不是修改函数的实参
123456789101112131415161718192021
// really badfunction handleThings(opts) {// No! We shouldn't mutate function arguments.// Double bad: if opts is falsy it'll be set to an object which may// be what you want but it can introduce subtle bugs.opts = opts || {};// ...}// still badfunction handleThings(opts) {if (opts === void 0) {opts = {};}// ...}// goodfunction handleThings(opts = {}) {// ...}
箭头函数 Arrow Functions
当必须使用函数表达式时(例如传递一个匿名函数时),请使用箭头函数
箭头函数提供了更简洁的语法,并且箭头函数中
this
对象的指向是不变的,this
对象绑定定义时所在的对象,这通常是我们想要的。如果该函数的逻辑非常复杂,请将该函数提取为一个函数声明。
123456789
// bad[1, 2, 3].map(function (x) {return x * x;});// good[1, 2, 3].map((x) => {return x * x});
- 总是用括号包裹参数,省略括号只适用于单个参数,并且还降低了程序的可读性
12345
// bad[1, 2, 3].map(x => x * x);// good[1, 2, 3].map((x) => x * x);
构造函数
总是使用
class
关键字,避免直接修改prototype
class
语法更简洁,也更易理解。
12345678910111213141516171819202122
// badfunction Queue(contents = []) {this._queue = [...contents];}Queue.prototype.pop = function() {const value = this._queue[0];this._queue.splice(0, 1);return value;}// goodclass Queue {constructor(contents = []) {this._queue = [...contents];}pop() {const value = this._queue[0];this._queue.splice(0, 1);return value;}}
使用
extends
关键字来继承这是一个内置的继承方式,并且不会破坏
instanceof
原型检查。
12345678910111213141516
// badconst inherits = require('inherits');function PeekableQueue(contents) {Queue.apply(this, contents);}inherits(PeekableQueue, Queue);PeekableQueue.prototype.peek = function() {return this._queue[0];}// goodclass PeekableQueue extends Queue {peek() {return this._queue[0];}}
- 在方法中返回
this
以方便链式调用
12345678910111213141516171819202122232425262728293031
// badJedi.prototype.jump = function() {this.jumping = true;return true;};Jedi.prototype.setHeight = function(height) {this.height = height;};const luke = new Jedi();luke.jump(); // => trueluke.setHeight(20); // => undefined// goodclass Jedi {jump() {this.jumping = true;return this;}setHeight(height) {this.height = height;return this;}}const luke = new Jedi();luke.jump().setHeight(20);
- 可以写一个自定义的toString()方法,但是确保它工作正常并且不会有副作用
12345678910111213
class Jedi {contructor(options = {}) {this.name = options.name || 'no name';}getName() {return this.name;}toString() {return `Jedi - ${this.getName()}`;}}
模块
总是在非标准的模块系统中使用标准的
import
和export
语法,我们总是可以将标准的模块语法转换成支持特定模块加载器的语法。模块是未来的趋势,那么我们为何不现在就开始使用。
1234567891011
// badconst AirbnbStyleGuide = require('./AirbnbStyleGuide');module.exports = AirbnbStyleGuide.es6;// okimport AirbnbStyleGuide from './AirbnbStyleGuide';export default AirbnbStyleGuide.es6;// bestimport { es6 } from './AirbnbStyleGuide';export default es6;
不要使用通配符
*
的import
这样确保了只有一个默认的
export
项
12345
// badimport * as AirbnbStyleGuide from './AirbnbStyleGuide';// goodimport AirbnbStyleGuide from './AirbnbStyleGuide';
不要直接从一个
import
上export
虽然一行代码看起来更简洁,但是有一个明确的
import
和一个明确的export
使得代码行为更加明确。
12345678
// bad// filename es6.jsexport default { es6 } from './airbnbStyleGuide';// good// filename es6.jsimport { es6 } from './AirbnbStyleGuide';export default es6;
Iterators 和 Generators
不要使用迭代器(Iterators)。优先使用 JavaScript 中
map
和reduce
这类高阶函数来代替for-of
循环处理纯函数的返回值更加容易并且没有副作用
123456789101112131415161718
const numbers = [1, 2, 3, 4, 5];// badlet sum = 0;for (let num of numbers) {sum += num;}sum === 15;// goodlet sum = 0;numbers.forEach((num) => sum += num);sum === 15;// best (use the functional force)const sum = numbers.reduce((total, num) => total + num, 0);sum === 15;
不要使用 generators
它们不太容易转换为 ES5 的语法。
属性
- 使用点
.
操作符来访问属性
12345678910
const luke = {jedi: true,age: 28};// badconst isJedi = luke['jedi'];// goodconst isJedi = luke.jedi;
- 当使用变量访问属性时使用中括号
[]
12345678910
var luke = {jedi: true,age: 28};function getProp(prop) {return luke[prop];}var isJedi = getProp('jedi');
变量
- 总是使用
const
来声明变量,否则将生成全局变量,我们应该避免污染全局命名空间
12345
// badsuperPower = new SuperPower();// goodconst superPower = new SuperPower();
为每个变量都使用
const
关键字声明这种方式更加容易添加新变量,并且不必担忧将
,
错误写成;
而导致生成全局变量。
123456789101112131415
// badconst items = getItems(),goSportsTeam = true,dragonball = 'z';// bad// (compare to above, and try to spot the mistake)const items = getItems(),goSportsTeam = true;dragonball = 'z';// goodconst items = getItems();const goSportsTeam = true;const dragonball = 'z';
- 将所有
const
变量放在一起,然后将所有let
变量放在一起
123456789101112131415161718
// badlet i, len, dragonball,items = getItems(),goSportsTeam = true;// badlet i;let items = getItems();let dragonball;let goSportsTeam = true;let len;// goodconst goSportsTeam = true;const items = getItems();let dragonball;let i;let length;
在必要的时候声明变量,并且将其放在合适的位置
let
和const
是块级作用域的,而不是函数作用域。
12345678910111213141516171819202122232425262728293031323334353637
// goodfunction() {test();console.log('doing stuff..');//..other stuff..const name = getName();if (name === 'test') {return false;}return name;}// badfunction() {const name = getName();if (!arguments.length) {return false;}return true;}// goodfunction() {if (!arguments.length) {return false;}const name = getName();return true;}
变量提升 Hoisting
- 通过
var
声明的变量将被提升到作用域的顶部,但他们的赋值不会被提升。通过const
和let
声明的变量不存在变量提升,这里有一个新概念,称为“暂时性死区( Temporal Dead Zones (TDZ))”。有必要理解typeof
不再是一个百分之百安全的操作。
123456789101112131415161718192021222324252627282930
// we know this wouldn't work (assuming there// is no notDefined global variable)function example() {console.log(notDefined); // => throws a ReferenceError}// creating a variable declaration after you// reference the variable will work due to// variable hoisting. Note: the assignment// value of `true` is not hoisted.function example() {console.log(declaredButNotAssigned); // => undefinedvar declaredButNotAssigned = true;}// The interpreter is hoisting the variable// declaration to the top of the scope,// which means our example could be rewritten as:function example() {let declaredButNotAssigned;console.log(declaredButNotAssigned); // => undefineddeclaredButNotAssigned = true;}// using const and letfunction example() {console.log(declaredButNotAssigned); // => throws a ReferenceErrorconsole.log(typeof declaredButNotAssigned); // => throws a ReferenceErrorconst declaredButNotAssigned = true;}
- 匿名函数表达式提升了对应的变量名,但赋值过程没有被提升
123456789
function example() {console.log(anonymous); // => undefinedanonymous(); // => TypeError anonymous is not a functionlet anonymous = function() {console.log('anonymous function expression');};}
- 命名的函数表达式提升了对应的变量名,函数名和函数体没有被提升
1234567891011121314151617181920212223
function example() {console.log(named); // => undefinednamed(); // => TypeError named is not a functionsuperPower(); // => ReferenceError superPower is not definedvar named = function superPower() {console.log('Flying');};}// the same is true when the function name// is the same as the variable name.function example() {console.log(named); // => undefinednamed(); // => TypeError named is not a functionvar named = function named() {console.log('named');}}
- 函数声明将被提升
1234567
function example() {superPower(); // => Flyingfunction superPower() {console.log('Flying');}}
- 更多细节可以参考 Ben Cherry 的 JavaScript Scoping & Hoisting
比较运算符和等号
- 使用
===
和!==
而不是==
和!=
比较运算通过
ToBoolean
强制转换并遵循一下规则:Object
-true
Undefined
-false
Null
-false
Booleans
- 被转换为对应的值Number
- 值为+0
,-0
,NaN
时为false
,否则为true
String
- 空字符串''
为false
,否则为true
1234
if ([0]) {// true// An array is an object, objects evaluate to true}
- 使用快捷方式
12345678910111213141516171819
// badif (name !== '') {// ...stuff...}// goodif (name) {// ...stuff...}// badif (collection.length > 0) {// ...stuff...}// goodif (collection.length) {// ...stuff...}
- 更多细节请阅读 Truth Equality and JavaScript
块
- 给所有多行的块使用大括号
12345678910111213141516171819
// badif (test)return false;// goodif (test) return false;// goodif (test) {return false;}// badfunction() { return false; }// goodfunction() {return false;}
- 使用
if...else
这样的多行块时,请将else
和if
的结束括号放在同一行
12345678910111213141516
// badif (test) {thing1();thing2();}else {thing3();}// goodif (test) {thing1();thing2();} else {thing3();}
注释
- 使用
/** ... */
进行多行注释,包括描述,指定类型以及参数值和返回值
123456789101112131415161718192021222324252627
// 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;}
- 使用
//
进行单行注释,将注释放在被注释对象的上面,并在注释之前保留一个空行
12345678910111213141516171819202122232425
// badconst active = true; // is current tab// good// is current tabconst active = true;// badfunction getType() {console.log('fetching type...');// set the default type to 'no type'const type = this._type || 'no type';return type;}// goodfunction getType() {console.log('fetching type...');// set the default type to 'no type'const type = this._type || 'no type';return type;}
- 使用
// FIXME:
来注释一个问题
1234567
function Calculator() {// FIXME: shouldn't use a global heretotal = 0;return this;}
- 使用
// TODO:
来注释一个问题的解决方案
1234567
function Calculator() {// TODO: total should be configurable by an options paramthis.total = 0;return this;}
空白
- 将
tab
设置为2
个空格缩进
1234567891011121314
// badfunction() {∙∙∙∙const name;}// badfunction() {∙const name;}// goodfunction() {∙∙const name;}
- 前大括号前放置一个空格
123456789101112131415161718192021
// 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'});
- 运算符之间用空格分隔
12345
// badconst x=y+5;// goodconst x = y + 5;
- 文件末尾使用单个换行符
1234
// bad(function(global) {// ...stuff...})(this);
12345
// bad(function(global) {// ...stuff...})(this);↵↵
1234
// good(function(global) {// ...stuff...})(this);↵
- 方法链式调用时保持适当的缩进,并且使用前置的
.
来表示该行是一个方法调用,而不是一个新语句
12345678910111213141516171819202122232425262728293031323334
// bad$('#items').find('.selected').highlight().end().find('.open').updateCount();// bad$('#items').find('selected').highlight().end().find('.open').updateCount();// good$('#items').find('.selected').highlight().end().find('.open').updateCount();// badconst 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);// goodconst 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);
- 在语句块之后和下一语句之前都保持一个空行
1234567891011121314151617181920212223242526272829303132
// badif (foo) {return bar;}return baz;// goodif (foo) {return bar;}return baz;// badconst obj = {foo: function() {},bar: function() {}};return obj;// goodconst obj = {foo: function() {},bar: function() {}};return obj;
逗号
- 不要将逗号放前面
1234567891011121314151617181920212223242526272829
// badconst story = [once, upon, aTime];// goodconst story = [once,upon,aTime];// badconst hero = {firstName: 'Bob', lastName: 'Parr', heroName: 'Mr. Incredible', superPower: 'strength'};// goodconst hero = {firstName: 'Bob',lastName: 'Parr',heroName: 'Mr. Incredible',superPower: 'strength'};
- 不要添加多余的逗号,否则将在 IE6/7 和 IE9 的怪异模式下导致错误。同时,某些 ES3 的实现会计算多数组的长度,这在 ES5 中有澄清
123456789101112131415161718192021
// badconst hero = {firstName: 'Kevin',lastName: 'Flynn',};const heroes = ['Batman','Superman',];// goodconst hero = {firstName: 'Kevin',lastName: 'Flynn'};const heroes = ['Batman','Superman'];
分号
- 句末一定要添加分号
1234567891011121314151617
// bad(function() {const name = 'Skywalker'return name})()// good(() => {const name = 'Skywalker';return name;})();// good (guards against the function becoming an argument when two files with IIFEs are concatenated);(() => {const name = 'Skywalker';return name;})();
类型转换
- 在语句的开始执行类型转换
- 字符串:
1234567
// => this.reviewScore = 9;// badconst totalScore = this.reviewScore + '';// goodconst totalScore = String(this.reviewScore);
- 对数字使用 parseInt 并且总是带上类型转换的基数
12345678910111213141516171819
const inputValue = '4';// badconst val = new Number(inputValue);// badconst val = +inputValue;// badconst val = inputValue >> 0;// badconst val = parseInt(inputValue);// goodconst val = Number(inputValue);// goodconst val = parseInt(inputValue, 10);
- 不管是出于一些奇特的原因,还是
parseInt
是一个瓶颈而需要位运算来解决某些性能问题,请为你的代码注释为什么要这样做
1234567
// good/*** parseInt was the reason my code was slow.* Bitshifting the String to coerce it to a* Number made it a lot faster.*/const val = inputValue >> 0;
- 注意:使用位移运算时要特别小心。
Number
在 JavaScript 中表示为 64 位的值,但位移运算总是返回一个 32 位的整数(source),对大于 32 位的整数进行位移运算会导致意外的结果(讨论)。32 位最大整数为2,147,483,647
:
123
2147483647 >> 0 //=> 21474836472147483648 >> 0 //=> -21474836482147483649 >> 0 //=> -2147483647
- 布尔值
12345678910
var age = 0;// badvar hasAge = new Boolean(age);// goodvar hasAge = Boolean(age);// goodvar hasAge = !!age;
命名约定
- 避免单个字符名,让你的变量名有描述意义
123456789
// badfunction q() {// ...stuff...}// goodfunction query() {// ..stuff..}
- 命名对象、函数和实例时使用小驼峰命名规则
123456789101112131415
// 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'});
- 命名构造函数或类时使用大驼峰命名规则
12345678910111213141516171819
// badfunction user(options) {this.name = options.name;}const bad = new user({name: 'nope'});// goodclass User {constructor(options) {this.name = options.name;}}const good = new User({name: 'yup'});
- 命名私有属性时前面加个下划线
_
123456
// badthis.__firstName__ = 'Panda';this.firstName_ = 'Panda';// goodthis._firstName = 'Panda';
- 保存对
this
的引用时使用_this
1234567891011121314151617181920212223
// 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);};}
- 导出单一一个类时,确保你的文件名就是你的类名
123456789101112131415
// file contentsclass CheckBox {// ...}module.exports = CheckBox;// in some other file// badconst CheckBox = require('./checkBox');// badconst CheckBox = require('./check_box');// goodconst CheckBox = require('./CheckBox');
- 导出一个默认小驼峰命名的函数时,文件名应该就是导出的方法名
1234
function makeStyleGuide() {}export default makeStyleGuide;
- 导出单例、函数库或裸对象时,使用大驼峰命名规则
123456
const AirbnbStyleGuide = {es6: {}};export default AirbnbStyleGuide;
访问器
- 属性的访问器函数不是必须的
- 如果你确实有存取器函数的话使用
getVal()
和setVal('hello')
1234567891011
// baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25);
- 如果属性是布尔值,使用
isVal()
或hasVal()
123456789
// badif (!dragon.age()) {return false;}// goodif (!dragon.hasAge()) {return false;}
- 可以创建get()和set()函数,但是要保持一致性
12345678910111213
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];};
事件
- 当给事件附加数据时,传入一个哈希而不是原始值,这可以让后面的贡献者加入更多数据到事件数据里而不用找出并更新那个事件的事件处理器
12345678
// bad$(this).trigger('listingUpdated', listing.id);...$(this).on('listingUpdated', function(e, listingId) {// do something with listingId});
12345678
// good$(this).trigger('listingUpdated', { listingId : listing.id });...$(this).on('listingUpdated', function(e, data) {// do something with data.listingId});
jQuery
- 为 jQuery 对象命名时添加
$
前缀
12345
// badconst sidebar = $('.sidebar');// goodconst $sidebar = $('.sidebar');
- 缓存 jQuery 的查询结果
12345678910111213141516171819202122
// badfunction setSidebar() {$('.sidebar').hide();// ...stuff...$('.sidebar').css({'background-color': 'pink'});}// goodfunction setSidebar() {const $sidebar = $('.sidebar');$sidebar.hide();// ...stuff...$sidebar.css({'background-color': 'pink'});}
- 对DOM查询使用级联的
$('.sidebar ul')
或$('.sidebar ul')
,jsPerf - 在指定作用域进行查询时使用
find
1234567891011121314
// bad$('ul', '.sidebar').hide();// bad$('.sidebar').find('ul').hide();// good$('.sidebar ul').hide();// good$('.sidebar > ul').hide();// good$sidebar.find('ul').hide();
ECMAScript 5 兼容性
- ES6规范大全
- 开发规范:ES6开发规范
- ES6代码规范(整理)
- JavaScript ES6 规范
- 关于es5 , es6 规范
- ES6书写规范
- ES6规范之promise模式
- ES6 新特性范例大全
- ES6 新特性范例大全
- ES6 新特性范例大全
- ES6 新特性范例大全
- ES6 新特性范例大全
- es6转为es5:Babel下的ES6兼容性与规范
- ECMAScript 2015(ES6)规范中的promise
- 前端规范(ES6\BEM\OOCSS\SMACSS)
- CommonJS,AMD,CMD,ES6模块规范
- 网络协议规范大全
- JSR规范大全
- 29、ParamNameResolver参数解析
- 30、SQL片段的解析
- 377. Combination Sum IV
- SVN安装、MyEclipse安装SVN插件以及上传项目
- mysql安装及连接
- ES6规范大全
- 文章标题
- Angular2 父子路由问题
- 31、propertise解析之通用标记解析器与标记处理器
- uml关联符号说明
- 32、解析MetaObject
- Android基础--ListView的显示几种方式
- 1001. 求高精度幂
- 快速Android开发系列网络篇之Android-Async-Http