JavaScript样式指南(上)

202 阅读3分钟

主要包括以下二十二个方面:

1.Types
2.References
3.Objects
4.Arrays
5.Destructuring
6.Strings
7.Functions
8.箭头函数
9.类和构造函数
10.模块
11.迭代器和生成器
12.访问属性
13.变量
14.变量提升
15.比较运算符和相等
16.Blocks
17.控制语句
18.注解
19.分号
20.强制类型转换
21.命名约定
22.ES6

1.Types

1.1 访问基本类型时,可以直接使用它的值.
    stringnumberbooleannullundefinedsymbolbigint
    const foo = 1;
    let bar = foo;
    bar = 9;
    console.log(foo,bar); // => 1,9
1.2 当访问复杂类型时,要处理对其值的引用. 
        object、array、function
        const foo = [1,2];
        const bar = foo;
        bar[0] = 9;
        console.log(foo[0],bar[0]); // => 9,9

2.References

2.1 使用const定义你的常量,避免使用var.
  // bad
  var a = 1;
  var b = 2;

  //good
  const a = 1;
  const b = 2;
2.2使用 let 声明你的变量,避免使用var.
   // bad
   var count = 1;
   if (true) {
     count += 1;
   }
   
   // good
   let count = 1;
   if (true) {
     count += 1;
   }
2.3 不要在定义const 和 let 的块级作用域之外访问它们.
{
  let a = 1;
  const b = 2;
}
console.log(a);  //ReferenceError
console.log(b);  //ReferenceError

3.Objects

3.1 创建对象
// bad
const item = new Object();

// good
const item = {};
3.2 使用object方法的简写
// bad 
const atom = {
  value: 5,
  addValue: function(value) {
    return atom.value + value;
  },
};

// good 
const atom = {
  value: 5,
  addValue(value) {
    return atom.value + value;
  },
};
3.3使用object属性简写
const age = 18;

// bad
const obj = {
    age: age,
};

// good 
const obj = {
    age,
};
3.4 将对象的属性简写放在对象的开头
const age = 18;
const name = 'Tom';

// bad
const obj = {
  num:5,
  name,
  sex:'男',
  age,
};

// good 
const obj = {
  name,
  age,
  num:5,
  sex:'男',
};
3.5不要从目标对象访问Object原型方法,如hasOwnProperty、propertyIsEnumerable、isPrototypeOf等.因为这些方法可能会受到所讨论对象的属性影响,如考虑 {hasOwnProperty: false} or (Object.create(null)).

// bad
console.log(object.hasOwnProperty(key));

// good
console.log(Object.prototype.hasOwnProperty.call(object, key));

// best
const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.
console.log(has.call(object, key));
3.6 优先考虑使用对象扩展运算符合并对象,而非 Object.assign,对象扩展运算符语法更简洁,并且比Object.assign性能更好.
// very bad
const original = { a: 1, b: 2 };
const copy = Object.assign(original, { c: 3 }); // this mutates `original` ಠ_ಠ
delete copy.a; // so does this

// bad
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 }

// good
const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 }
const { a, ...noA } = copy; // noA => { b: 2, c: 3 }

4.Arrays

4.1 数组声明
 // bad 
 const item = new Array();
 
 // good 
 const item = [];
4.2 使用Array的push方法添加数组元素.
const someStack = [];

// bad
someStack[someStack.lenght] = 'abracada';

// good 
someStack.push('abracada');
4.3 使用spreads ... 赋值数组.
// bad
const len = items.length;
const itemsCopy = [];
let i;

for (i = 0; i < len; i += 1) {
  itemsCopy[i] = items[i];
}

// good
const itemsCopy = [...items];

5.Destructuring

5.1 在访问和使用对象多个属性时,请使用对象解构赋值。解构赋值使你不必为这些属性创建临时引用,也不必重复访问该对象,减少代码重复,可读性更高,产生bug的机会越低.

// bad
function getFullName(user) {
  const firstName = user.firstName;
  const lastName = user.lastName;

  return `${firstName} ${lastName}`;
}

// good
function getFullName(user) {
  const { firstName, lastName } = user;
  return `${firstName} ${lastName}`;
}

// best
function getFullName({ firstName, lastName }) {
  return `${firstName} ${lastName}`;
}
5.2 数组解构赋值
const arr = [1, 2, 3, 4];

// bad
const first = arr[0];
const second = arr[1];

// good
const [first, second] = arr;

6.Strings

6.1 string的值使用单引号 ''.
// bad
const name = "Capt. Janeway";

// bad - 模板字符串应该包含变量
const name = `Capt. Janeway`;

// good
const name = 'Capt. Janeway';
6.2 使用 `` 拼接字符串而非 + .
// bad
function sayHi(name) {
  return 'How are you, ' + name + '?';
}

// bad
function sayHi(name) {
  return ['How are you, ', name, '?'].join();
}

// bad
function sayHi(name) {
  return `How are you, ${ name }?`;
}

// good
function sayHi(name) {
  return `How are you, ${name}?`;
}

7.Functions

7.1 不要使用arguments,选择使用rest syntax ... 代替, ...明确表示需要哪些参数,另外,rest参数是一个真正的数组,而不仅仅是类似数组的参数.
	// bad
    function concatenateAll() {
      const args = Array.prototype.slice.call(arguments);
      return args.join('');
    }

    // good
    function concatenateAll(...args) {
      return args.join('');
	}
7.2 使用默认参数语法,而不是改变函数参数.
    // really bad
    function handleThings(opts) {
      opts = opts || {};
      // ...
    }

    // still bad
    function handleThings(opts) {
      if (opts === void 0) {
        opts = {};
      }
      // ...
    }

    // good
    function handleThings(opts = {}) {
      // ...
    }
仅作个人学习使用,原文地址:https://github.com/airbnb/javascript#table-of-contents