标签:blog http io ar color os 使用 sp java
原文转自:http://blog.jobbole.com/79484/
Airbnb 是一家位于美国旧金山的公司,本文是其内部的 JavaScript 风格指南/编码规范,在 Github 上有 11,000+ Star,2100+ fork,前端开发者可参考。
stringnumberbooleannullundefined
|
1
2
3
4
5
6
|
var foo = 1,bar = foo;bar = 9;console.log(foo, bar); // => 1, 9 |
objectarrayfunction|
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
|
// badvar item = new Object();// goodvar item = {}; |
|
1
2
3
4
5
6
7
8
9
10
11
|
// badvar superman = { default: { clark: ‘kent‘ }, private: true};// goodvar superman = { defaults: { clark: ‘kent‘ }, hidden: true}; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// badvar superman = { class: ‘alien‘};// badvar superman = { klass: ‘alien‘};// goodvar superman = { type: ‘alien‘}; |
|
1
2
3
4
5
|
// badvar items = new Array();// goodvar items = []; |
|
1
2
3
4
5
6
7
|
var someStack = [];// badsomeStack[someStack.length] = ‘abracadabra‘;// goodsomeStack.push(‘abracadabra‘); |
|
1
2
3
4
5
6
7
8
9
10
11
|
var len = items.length, itemsCopy = [], i;// badfor (i = 0; i < len; i++) { itemsCopy[i] = items[i];}// gooditemsCopy = 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
|
// badvar name = "Bob Parr";// goodvar name = ‘Bob Parr‘;// badvar fullName = "Bob " + this.lastName;// goodvar fullName = ‘Bob ‘ + this.lastName; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
// 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 dowith 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.‘; |
|
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;// badfunction inbox(messages) { items = ‘<ul>‘; for (i = 0; i < length; i++) { items += ‘<li>‘ + messages[i].message + ‘</li>‘; } return items + ‘</ul>‘;}// goodfunction 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 expressionvar anonymous = function() { return true;};// named function expressionvar 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
|
// badif (currentUser) { function test() { console.log(‘Nope.‘); }}// goodvar test;if (currentUser) { test = function test() { console.log(‘Yup.‘); };} |
|
1
2
3
4
5
6
7
8
9
|
// badfunction nope(name, options, arguments) { // ...stuff...}// goodfunction yup(name, options, args) { // ...stuff...} |
|
1
2
3
4
5
6
7
8
9
10
|
var luke = { jedi: true, age: 28};// badvar isJedi = luke[‘jedi‘];// goodvar 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
|
// badsuperPower = new SuperPower();// goodvar superPower = new SuperPower(); |
|
1
2
3
4
5
6
7
8
9
|
// badvar items = getItems();var goSportsTeam = true;var dragonball = ‘z‘;// goodvar items = getItems(), goSportsTeam = true, dragonball = ‘z‘; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
// badvar i, len, dragonball, items = getItems(), goSportsTeam = true;// badvar i, items = getItems(), dragonball, goSportsTeam = true, len;// goodvar 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
|
// badfunction() { test(); console.log(‘doing stuff..‘); //..other stuff.. var name = getName(); if (name === ‘test‘) { return false; } return name;}// goodfunction() { var name = getName(); test(); console.log(‘doing stuff..‘); //..other stuff.. if (name === ‘test‘) { return false; } return name;}// badfunction() { var name = getName(); if (!arguments.length) { return false; } return true;}// goodfunction() { 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
|
// badif (name !== ‘‘) { // ...stuff...}// goodif (name) { // ...stuff...}// badif (collection.length > 0) { // ...stuff...}// goodif (collection.length) { // ...stuff...} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
// badif (test) return false;// goodif (test) return false;// goodif (test) { return false;}// badfunction() { return false; }// goodfunction() { 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> 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;} |
|
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
|
// badvar active = true; // is current tab// good// is current tabvar active = true;// badfunction getType() { console.log(‘fetching type...‘); // set the default type to ‘no type‘ var type = this._type || ‘no type‘; return type;}// goodfunction 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
|
// badfunction() {????var name;}// badfunction() {?var name;}// goodfunction() {??var name;} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
// 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‘}); |
|
1
2
3
4
5
|
// badvar x=y+5;// goodvar 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();// badvar 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);// goodvar 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
|
// badvar once , upon , aTime;// goodvar once, upon, aTime;// badvar hero = { firstName: ‘Bob‘ , lastName: ‘Parr‘ , heroName: ‘Mr. Incredible‘ , superPower: ‘strength‘};// goodvar 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;// badvar totalScore = this.reviewScore + ‘‘;// goodvar totalScore = ‘‘ + this.reviewScore;// badvar totalScore = ‘‘ + this.reviewScore + ‘ total score‘;// goodvar 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‘;// badvar val = new Number(inputValue);// badvar val = +inputValue;// badvar val = inputValue >> 0;// badvar val = parseInt(inputValue);// goodvar val = Number(inputValue);// goodvar 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 //=> 21474836472147483648 >> 0 //=> -21474836482147483649 >> 0 //=> -2147483647 |
|
1
2
3
4
5
6
7
8
9
10
|
var age = 0;// badvar hasAge = new Boolean(age);// goodvar hasAge = Boolean(age);// goodvar hasAge = !!age; |
|
1
2
3
4
5
6
7
8
9
|
// badfunction q() { // ...stuff...}// goodfunction query() { // ..stuff..} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// badvar OBJEcttsssss = {};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‘}); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// badfunction user(options) { this.name = options.name;}var bad = new user({ name: ‘nope‘});// goodfunction User(options) { this.name = options.name;}var good = new User({ name: ‘yup‘}); |
|
1
2
3
4
5
6
|
// badthis.__firstName__ = ‘Panda‘;this.firstName_ = ‘Panda‘;// goodthis._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
|
// 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); };} |
|
1
2
3
4
5
6
7
8
9
|
// badvar log = function(msg) { console.log(msg);};// goodvar log = function log(msg) { console.log(msg);}; |
|
1
2
3
4
5
6
7
8
9
10
11
|
// baddragon.age();// gooddragon.getAge();// baddragon.age(25);// gooddragon.setAge(25); |
如果这个属性是boolean,使用isVal() 或者 hasVal()
|
1
2
3
4
5
6
7
8
9
|
// badif (!dragon.age()) { return false;}// goodif (!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‘);}// badJedi.prototype = { fight: function fight() { console.log(‘fighting‘); }, block: function block() { console.log(‘blocking‘); }};// goodJedi.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
|
// badJedi.prototype.jump = function() { this.jumping = true; return true;};Jedi.prototype.setHeight = function(height) { this.height = height;};var luke = new Jedi();luke.jump(); // => trueluke.setHeight(20); // => undefined// goodJedi.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
|
// badvar sidebar = $(‘.sidebar‘);// goodvar $sidebar = $(‘.sidebar‘); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// badfunction setSidebar() { $(‘.sidebar‘).hide(); // ...stuff... $(‘.sidebar‘).css({ ‘background-color‘: ‘pink‘ });}// goodfunction 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