标签:blog http io ar color os 使用 sp java
原文转自:http://blog.jobbole.com/79484/
Airbnb 是一家位于美国旧金山的公司,本文是其内部的 JavaScript 风格指南/编码规范,在 Github 上有 11,000+ Star,2100+ fork,前端开发者可参考。
string
number
boolean
null
undefined
1
2
3
4
5
6
|
var foo = 1 , bar = foo; bar = 9 ; console.log(foo, bar); // => 1, 9 |
object
array
function
1
2
3
4
5
6
|
var foo = [ 1 , 2 ], bar = foo; bar[ 0 ] = 9 ; console.log(foo[ 0 ], bar[ 0 ]); // => 9, 9 |
1
2
3
4
5
|
// bad var item = new Object (); // good var item = {}; |
1
2
3
4
5
6
7
8
9
10
11
|
// bad var superman = { default : { clark: ‘kent‘ }, private : true }; // good var superman = { defaults: { clark: ‘kent‘ }, hidden: true }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad var superman = { class : ‘alien‘ }; // bad var superman = { klass: ‘alien‘ }; // good var superman = { type: ‘alien‘ }; |
1
2
3
4
5
|
// bad var items = new Array (); // good var items = []; |
1
2
3
4
5
6
7
|
var someStack = []; // bad someStack[someStack.length] = ‘abracadabra‘ ; // good someStack.push( ‘abracadabra‘ ); |
1
2
3
4
5
6
7
8
9
10
11
|
var len = items.length, itemsCopy = [], i; // bad for (i = 0 ; i < len; i++) { itemsCopy[i] = items[i]; } // good itemsCopy = items.slice(); |
1
2
3
4
|
function trigger() { var args = Array .prototype.slice.call(arguments); ... } |
1
2
3
4
5
6
7
8
9
10
11
|
// bad var name = "Bob Parr" ; // good var name = ‘Bob Parr‘ ; // bad var fullName = "Bob " + this .lastName; // good var fullName = ‘Bob ‘ + this .lastName; |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// bad var 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.‘ ; // bad var 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.‘; // good var 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.‘ ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
var items, messages, length, i; messages = [{ state: ‘success‘ , message: ‘This one worked.‘ }, { state: ‘success‘ , message: ‘This one worked as well.‘ }, { state: ‘error‘ , message: ‘This one did not work.‘ }]; length = messages.length; // bad function inbox(messages) { items = ‘<ul>‘ ; for (i = 0 ; i < length; i++) { items += ‘<li>‘ + messages[i].message + ‘</li>‘ ; } return items + ‘</ul>‘ ; } // good function inbox(messages) { items = []; for (i = 0 ; i < length; i++) { items[i] = messages[i].message; } return ‘<ul><li>‘ + items.join( ‘</li><li>‘ ) + ‘</li></ul>‘ ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// anonymous function expression var anonymous = function () { return true ; }; // named function expression var named = function named() { return true ; }; // immediately-invoked function expression (IIFE) ( function () { console.log( ‘Welcome to the Internet. Please follow me.‘ ); })(); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad if (currentUser) { function test() { console.log( ‘Nope.‘ ); } } // good var test; if (currentUser) { test = function test() { console.log( ‘Yup.‘ ); }; } |
1
2
3
4
5
6
7
8
9
|
// bad function nope(name, options, arguments) { // ...stuff... } // good function yup(name, options, args) { // ...stuff... } |
1
2
3
4
5
6
7
8
9
10
|
var luke = { jedi: true , age: 28 }; // bad var isJedi = luke[ ‘jedi‘ ]; // good var isJedi = luke.jedi; |
1
2
3
4
5
6
7
8
9
10
|
var luke = { jedi: true , age: 28 }; function getProp(prop) { return luke[prop]; } var isJedi = getProp( ‘jedi‘ ); |
1
2
3
4
5
|
// bad superPower = new SuperPower(); // good var superPower = new SuperPower(); |
1
2
3
4
5
6
7
8
9
|
// bad var items = getItems(); var goSportsTeam = true ; var dragonball = ‘z‘ ; // good var items = getItems(), goSportsTeam = true , dragonball = ‘z‘ ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// bad var i, len, dragonball, items = getItems(), goSportsTeam = true ; // bad var i, items = getItems(), dragonball, goSportsTeam = true , len; // good var items = getItems(), goSportsTeam = true , dragonball, length, i; · |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
// bad function () { test(); console.log( ‘doing stuff..‘ ); //..other stuff.. var name = getName(); if (name === ‘test‘ ) { return false ; } return name; } // good function () { var name = getName(); test(); console.log( ‘doing stuff..‘ ); //..other stuff.. if (name === ‘test‘ ) { return false ; } return name; } // bad function () { var name = getName(); if (!arguments.length) { return false ; } return true ; } // good function () { if (!arguments.length) { return false ; } var name = getName(); return true ; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 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); // => undefined var 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() { var declaredButNotAssigned; console.log(declaredButNotAssigned); // => undefined declaredButNotAssigned = true ; } |
1
2
3
4
5
6
7
8
9
|
· function example() { console.log(anonymous); // => undefined anonymous(); // => TypeError anonymous is not a function var anonymous = function () { console.log( ‘anonymous function expression‘ ); }; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
function example() { console.log(named); // => undefined named(); // => TypeError named is not a function superPower(); // => ReferenceError superPower is not defined var 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); // => undefined named(); // => TypeError named is not a function var named = function named() { console.log( ‘named‘ ); } } |
1
2
3
4
5
6
7
|
function example() { superPower(); // => Flying function superPower() { console.log( ‘Flying‘ ); } } |
‘‘
返回 false 其他返回true
1
2
3
4
|
if ([ 0 ]) { // true // An array is an object, objects evaluate to true } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// bad if (name !== ‘‘ ) { // ...stuff... } // good if (name) { // ...stuff... } // bad if (collection.length > 0 ) { // ...stuff... } // good if (collection.length) { // ...stuff... } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// bad if (test) return false ; // good if (test) return false ; // good if (test) { return false ; } // bad function () { return false ; } // good function () { return false ; } |
/** ... */
,包括描述,指定类型、所有参数的值和返回值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// 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; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// 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; } |
// FIXME:
来标记问题
1
2
3
4
5
6
7
|
function Calculator() { // FIXME: shouldn‘t use a global here total = 0 ; return this ; } |
1
2
3
4
5
6
7
|
function Calculator() { // TODO: total should be configurable by an options param this .total = 0 ; return this ; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad function () { ???? var name; } // bad function () { ? var name; } // good function () { ?? var name; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// 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‘ }); |
1
2
3
4
5
|
// bad var x=y+ 5 ; // good var x = y + 5 ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad ( function (global) { // ...stuff... })( this ); // bad ( function (global) { // ...stuff... })( this ); // good ( function (global) { // ...stuff... })( this ) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
// 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); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
// 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‘ }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// bad var hero = { firstName: ‘Kevin‘ , lastName: ‘Flynn‘ , }; var heroes = [ ‘Batman‘ , ‘Superman‘ , ]; // good var hero = { firstName: ‘Kevin‘ , lastName: ‘Flynn‘ }; var heroes = [ ‘Batman‘ , ‘Superman‘ ]; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// bad ( function () { var name = ‘Skywalker‘ return name })() // good ( function () { var name = ‘Skywalker‘ ; return name; })(); // good (guards against the function becoming an argument when two files with IIFEs are concatenated) ;( function () { var name = ‘Skywalker‘ ; return name; })(); |
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// => 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
对
Numbers
型进行强制转型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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 ); |
parseInt
是你的瓶颈,出于性能考虑你需要使用
位移,那么留下你的注释来解释原因。
1
2
3
4
5
6
7
|
// 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 ; |
1
2
3
|
2147483647 >> 0 //=> 2147483647 2147483648 >> 0 //=> -2147483648 2147483649 >> 0 //=> -2147483647 |
1
2
3
4
5
6
7
8
9
10
|
var age = 0 ; // bad var hasAge = new Boolean (age); // good var hasAge = Boolean (age); // good var hasAge = !!age; |
1
2
3
4
5
6
7
8
9
|
// bad function q() { // ...stuff... } // good function query() { // ..stuff.. } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad var OBJEcttsssss = {}; 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‘ }); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// 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‘ }); |
1
2
3
4
5
6
|
// bad this .__firstName__ = ‘Panda‘ ; this .firstName_ = ‘Panda‘ ; // good this ._firstName = ‘Panda‘ ; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
// 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); }; } |
1
2
3
4
5
6
7
8
9
|
// bad var log = function (msg) { console.log(msg); }; // good var log = function log(msg) { console.log(msg); }; |
1
2
3
4
5
6
7
8
9
10
11
|
// bad dragon.age(); // good dragon.getAge(); // bad dragon.age( 25 ); // good dragon.setAge( 25 ); |
如果这个属性是boolean,使用isVal() 或者 hasVal()
1
2
3
4
5
6
7
8
9
|
// bad if (!dragon.age()) { return false ; } // good if (!dragon.hasAge()) { return false ; } |
.也可以使用get() 和 set()函数来创建,但是必须一致。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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]; }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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‘ ); }; |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
// 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 ); |
1
2
3
4
5
6
7
8
9
10
11
12
|
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(); }; |
1
2
3
4
5
6
7
8
|
// bad $( this ).trigger( ‘listingUpdated‘ , listing.id); ... $( this ).on( ‘listingUpdated‘ , function (e, listingId) { // do something with listingId }); |
更好的方式:
1
2
3
4
5
6
7
8
|
// good $( this ).trigger( ‘listingUpdated‘ , { listingId : listing.id }); ... $( this ).on( ‘listingUpdated‘ , function (e, data) { // do something with data.listingId }); |
noConflict()
的方法,使模块输出早期版本并返回。
‘use strict‘
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// 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 ); |
1
2
3
4
5
|
// bad var sidebar = $( ‘.sidebar‘ ); // good var $sidebar = $( ‘.sidebar‘ ); |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// 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‘ }); } |
$(‘.sidebar ul‘)
或
parent > child $(‘.sidebar > ul‘)
. jsPerf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// bad $( ‘ul‘ , ‘.sidebar‘ ).hide(); // bad $( ‘.sidebar‘ ).find( ‘ul‘ ).hide(); // good $( ‘.sidebar ul‘ ).hide(); // good $( ‘.sidebar > ul‘ ).hide(); // good $sidebar.find( ‘ul‘ ).hide(); |
【转】JavaScript 风格指南/编码规范(Airbnb公司版)
标签:blog http io ar color os 使用 sp java
原文地址:http://www.cnblogs.com/ricky52529/p/4107386.html