编写一致的符合习惯的javascript

本文转自我司的编码规范~

====

引言

将要叙述的这些原则旨对javascript开发的风格做指导,并非指定性的规则需绝对服从。如果需要找出一条必须遵循的原则,应该是保持代码的一致性和风格统一
除去对代码的可读性、可维护性有益外,同时可以减少很多代码提交解决冲突合并时产生的不必要的麻烦。

代码风格

空格

  • 不要混用tab 和 空格.
  • 在开始项目编码之前制定缩进规则,使用空格缩进还是tab缩进,并且严格贯彻下去。
    • 建议统一使用空格缩进(2spaces),使用编辑器的设置tab键为空格空进以强制执行。
  • 如果你的编辑器支持设置“显示隐藏字符”的话,建议打开它。好处在于:
    • 强制代码格式统一
    • 去除行尾空字符
    • 去除空行空字符Eliminating blank line whitespace
    • 代码提交比较差异时更方便阅读

Syntax美化

Syntax美化包括空格的规则、换行的规则,以及其他语法层面上的书写格式,以方便阅读为准。可以使用编辑器的格式化插件来达到格式美化的目的,项目开发人员需要统一插件格式的规则,以避免提交代码时格式不统一而产生的不必要的麻烦。
[插件https://github.com/akalongman/sublimetext-codeformatter|SublimeText Code Formatter](https://github.com/akalongman/sublimetext-codeformatter|SublimeText Code Formatter)

语言规则

变量

  • 声明变量时应该使用var。不这样做会得到全局变量,从而污染了全局命名空间。
  • 使用一个 var 以及新行声明多个变量,缩进4个空格
  • 最后再声明未赋值的变量,当以后你想给一个依赖之前已赋值变量的变量时很有用。
  • 不一定严格按照只是用一个var声明变量的规则,可以按照变量的相关性分组声明。
     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;
}

函数

  • 不要在块内定义functions。
//Do not do this:

if (x) {
  function foo() {}
}
//Do this
var foo;
if(x) {
  foo = function(){};
}
  • 函数表达式:
// 匿名函数表达式
var anonymous = function() {
  return true;
};

// 有名函数表达式
var named = function named() {
  return true;
};

// 立即调用函数表达式
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();
  • 绝对不要把参数命名为 arguments, 这将会逾越函数作用域内传过来的 arguments 对象.
// bad
function nope(name, options, arguments) {
  // ...stuff...
}

// good
function yup(name, options, args) {
  // ...stuff...
}

字符串

  • 对字符串使用单引号 '
// bad
var name = "Bob Parr";

// good
var name = 'Bob Parr';

// bad
var fullName = "Bob " + this.lastName;

// good
var fullName = 'Bob ' + this.lastName;
  • 超过80个字符的字符串应该使用字符串连接换行

  • 果过度使用,长字符串连接可能会对性能有影响.

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

逗号

  • 不要将逗号放前面
// 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'
};
  • 不要加多余的逗号
// 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;
  • 对数字使用 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);

// with caution
/**
 * parseInt was the reason my code was slow.
 * Bitshifting the String to coerce it to a
 * Number made it a lot faster. But it reduces the readability.
 */
var val = inputValue >> 0;

相等性

  • 优先选择严格的 “ === ” 做相等性判断,但是当检查是否是undefined 或者 null时, 可以使用“ == ”。

命名规则

  • 避免单个字符名,让你的变量名有描述意义。变量一般用名词, 函数一般使用动词,若函数返回boolean则可以用is或者has开头。常量使用全大写以下划线链接。
//good
var PI = 3.1415926;
// 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);
  };
}

其他

  • Prefer this.foo = null than delete this.foo
  • 小心使用switch语句
  • 不要轻易扩展修改builtin类型的行为
  • 谨慎使用保留字作为object属性名(已经吃过亏了)
  • 避免使用with

参考资料

posted @ 2017-07-28 17:58  Liaofy  阅读(255)  评论(0编辑  收藏  举报