javascript code style

javascript代码作风

泉源:https://github.com/airbnb/javascript

Objects 对象

javascript// bad
var item = new Object();

// good
var item = {};

//不要运用保留字作为对象属性,IE8不支持。
// bad
var superman = {
  default: { clark: 'kent' },
  private: true
};

// good
var superman = {
  defaults: { clark: 'kent' },
  hidden: true
};


Arrays 数组

javascript// bad
var items = new Array();

// good
var items = [];

//运用push增加数组元素
var someStack = [];
// bad
someStack[someStack.length] = 'abracadabra';

// good
someStack.push('abracadabra');

//复制数组的最快要领
var len = items.length;
var itemsCopy = [];
var i;
// bad
for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
itemsCopy = items.slice();

//转换array-like object(如:{1:'xx',2:'yy',length:2}) 成数组
var args = Array.prototype.slice.call(arguments);

Strings 字符串

javascript//运用单引号
// bad
var name = "Bob Parr";
// good
var name = 'Bob Parr';

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

// 运用`+`举行换行
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
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] = '<li>' + messages[i].message + '</li>';
  }

  return '

<ul>' + items.join('') + '</ul>

';
}

Functions 函数

javascript// 运用自实行函数
// immediately-invoked function expression (IIFE)
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//型参别用`arguments`
// bad
function nope(name, options, arguments) {
  // ...stuff...
}

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

Properties属性

javascript
var luke = { jedi: true, age: 28 }; // bad var isJedi = luke['jedi']; //平常状况运用`.`挪用, // good var isJedi = luke.jedi; function getProp(prop) { //属性是变量,运用`[]`挪用 return luke[prop]; } var isJedi = getProp('jedi');

Variables 变量

javascript
//运用var声明变量 // bad superPower = new SuperPower(); // good var superPower = new SuperPower(); //不必`,`支解变量 // bad // (compare to above, and try to spot the mistake) var items = getItems(), goSportsTeam = true; dragonball = 'z'; // good var items = getItems(); var goSportsTeam = true; var dragonball = 'z'; //声明未赋值变量在后面 // bad var i; var items = getItems(); var dragonball; var goSportsTeam = true; var len; // good var items = getItems(); var goSportsTeam = true; var dragonball; var length; var i; //函数内变量声明定义只管放最前面,除非有函数最先有推断`return false`, // 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; }

Equality 比较操纵

javascript// bad
if (name !== '') {
  // ...stuff...
}

// good
if (name) {
  // ...stuff...
}

// bad
if (collection.length > 0) {
  // ...stuff...
}

// good
if (collection.length) {
  // ...stuff...
}

Blocks 块

javascript// bad
if (test)
  return false;

// good
if (test) return false;

// good
if (test) {
  return false;
}

// bad
function() { return false; }

// good
function() {
  return false;
}

Comments 解释

javascript// 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;
}


// 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;
}

Type Casting 花样转换

javascript//  => 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';

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

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

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

Naming Conventions 定名商定

javascript// bad
function q() {
  // ...stuff...
}

//名字要有语意
// good
function query() {
  // ..stuff..
}

// bad
var OBJEcttsssss = {};
var this_is_my_object = {};

//驼峰定名
// good
var thisIsMyObject = {};
function thisIsMyFunction() {}

// bad
function user(options) {
  this.name = options.name;
}

//组织函数大写
// good
function User(options) {
  this.name = options.name;
}

// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';

//私有属性用`_`开首
// good
this._firstName = 'Panda';

// bad
function() {
  var self = this;
  return function() {
    console.log(self);
  };
}

// bad
function() {
  var that = this;
  return function() {
    console.log(that);
  };
}

//保留挪用者`this`为`_this`
// good
function() {
  var _this = this;
  return function() {
    console.log(_this);
  };
}

Constructors 组织函数

javascriptfunction Jedi() {
  console.log('new jedi');
}

// bad
Jedi.prototype = {
  fight: function fight() {
    console.log('fighting');
  }
};

// good
Jedi.prototype.fight = function fight() {
  console.log('fighting');
};

Events 事宜

javascript// bad
$(this).trigger('listingUpdated', listing.id);

...

$(this).on('listingUpdated', function(e, listingId) {
  // do something with listingId
});

//通报id时用对象包裹后再传
// good
$(this).trigger('listingUpdated', { listingId : listing.id });

...

$(this).on('listingUpdated', function(e, data) {
  // do something with data.listingId
});

Modules 模块

  • 申明文件途径
  • 文件名运用驼峰定名
  • 开首加上一个 `!
  • 模块中运用'use strict'严厉形式
  • 运用noConflict()无争执的输出
javascript// 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);
    原文作者:caicai
    原文地址: https://segmentfault.com/a/1190000002647927
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞