JavaScript 风格指南/编码规范(Airbnb公司版)一

本文档介绍了Airbnb公司的JavaScript编码规范,包括基本类型的使用、对象和数组的创建及操作建议、字符串处理技巧以及函数定义的最佳实践等内容,旨在帮助前端开发者编写高质量的JavaScript代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Airbnb 是一家位于美国旧金山的公司,本文是其内部的 JavaScript 风格指南/编码规范,在 Github 上有 11,000+ Star,2100+ fork,前端开发者可参考。

基本类型

  • 当你访问基本类型时,你是直接对它的值进行操作。
  • string
  • number
  • boolean
  • null
  • undefined
var foo = 1,
bar = foo;
 
bar = 9;
 
console.log(foo, bar); // => 1, 9

  • object
  • array
  • function
var foo = [1, 2],
bar = foo;
 
bar[0] = 9;
 
console.log(foo[0], bar[0]); // => 9, 9

对象

  • 使用字面量语法来创建对象
// bad
var item = new Object();
 
// good
var item = {};

  • 不要使用保留字作为“键值”,因为在IE8不能运行。More info
// bad
var superman = {
  default: { clark: 'kent' },
  private: true
};
 
// good
var superman = {
  defaults: { clark: 'kent' },
  hidden: true
};

  • 使用容易理解的同义词来替代保留字
// bad
var superman = {
  class: 'alien'
};
 
// bad
var superman = {
  klass: 'alien'
};
 
// good
var superman = {
  type: 'alien'
};

  • 数组

  • 使用字面量语法来创建数组
// bad
var items = new Array();
 
// good
var items = [];

  • 如果你不知道数组长度,数组添加成员使用push方法。
var someStack = [];
 
// bad
someStack[someStack.length] = 'abracadabra';
 
// good
someStack.push('abracadabra');

  • 当你需要复制一个数组时,使用数组的slice方法。jsPerf
var len = items.length,
    itemsCopy = [],
    i;
 
// bad
for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}
 
// good
itemsCopy = items.slice();

  • 当你需要把“类似数组对象”转为数组时,使用数组的slice方法。
function trigger() {
  var args = Array.prototype.slice.call(arguments);
  ...
}

  • 字符串

  • 字符串使用单引号‘’
// bad
var name = "Bob Parr";
 
// good
var name = 'Bob Parr';
 
// bad
var fullName = "Bob " + this.lastName;
 
// good
var fullName = 'Bob ' + this.lastName;

  • 大于80个元素的字符串需要通过分隔符进行多行操作。
  • 注意:如果在长字符串中过度使用分隔符会影响性能。. jsPerf & Discussion
// 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.';

  • 通过编程的方式创建字符串,应该使用数组的join方法,而不是字符串链接方法。特别是对于IE而言。 jsPerf.

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>';

  • 函数

  • 函数表达式
// 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.');
})();

  • 不要直接在非函数块(if,while等)里声明一个函数,最好将函数赋值给一个变量。虽然浏览器允许你在非函数块中声明函数,但是由于不同的浏览器对Javascript的解析方式不同,这样做就很可能造成麻烦。
  • 注意:ECMA-262 将块定义为一组语句,而函数声明不是语句。Read ECMA-262′s note on this issue
// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}
 
// good
var test;
if (currentUser) {
  test = function test() {
    console.log('Yup.');
  };
}

  • 不要将参数命名为arguments,它将在每个函数的作用范围内优先于arguments对象。
// bad
function nope(name, options, arguments) {
  // ...stuff...
}
 
// good
function yup(name, options, args) {
  // ...stuff...
}

  • 属性

  • 使用点符号 . 来访问属性
var luke = {
  jedi: true,
  age: 28
};
 
// bad
var isJedi = luke['jedi'];
 
// good
var isJedi = luke.jedi;

  • 当你在变量中访问属性时,使用[ ]符号
var luke = {
  jedi: true,
  age: 28
};
 
function getProp(prop) {
  return luke[prop];
}
 
var isJedi = getProp('jedi');

  • 变量

  • 使用var来声明变量,否则将声明全局变量,我们需要尽量避免污染全局命名空间,Captain Planet这样警告过我们。
// bad
superPower = new SuperPower();
 
// good
var superPower = new SuperPower();

  • 多个变量时只使用一个var声明,每个变量占一新行。
// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';
 
// good
var items = getItems(),
    goSportsTeam = true,
    dragonball = 'z';

  • 最后再声明未赋值的变量,这对你之后需要依赖之前变量的变量赋值会有帮助。
// 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;

  • 在范围内将变量赋值置顶,这有助于避免变量声明和赋值提升相关的问题
// 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;
}


来源 http://blog.jobbole.com/79484/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值