《爱彼迎JS风格指南》摘要

245 阅读1分钟

根据爱彼迎JS风格指南(Airbnb JavaScript Style Guide)链接,从中我摘选了之前未注意到的风格,作为后期开发的提醒。

避免不必要的三目表达式。 eslint: no-unneeded-ternary

// bad
const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? false : true;

// good
const foo = a || b;
const bar = !!c;
const baz = !c;

如果你使用的是 if 和 else 的多行代码块,则将 else 语句放在 if 块闭括号同一行的位置。 eslint: brace-style

// bad
if (test) {
  thing1();
  thing2();
}
else {
  thing3();
}

// good
if (test) {
  thing1();
  thing2();
} else {
  thing3();
}

不要使用选择操作符代替控制语句。

// bad
!isRunning && startRunning();

// good
if (!isRunning) {
  startRunning();
}

在控制语句(if, while 等)开始括号之前放置一个空格。 在函数调用和声明中,在参数列表和函数名之间没有空格。 eslint: keyword-spacing

// bad
if(isJedi) {
  fight ();
}

// good
if (isJedi) {
  fight();
}

// bad
function fight () {
  console.log ('Swooosh!');
}

// good
function fight() {
  console.log('Swooosh!');
}复制代码

用空格分离操作符。 eslint: space-infix-ops

// bad
const x=y+5;

// good
const x = y + 5;复制代码

添加尾随逗号: 可以 eslint: comma-dangle

// bad - 没有尾随逗号的 git 差异
const hero = {
     firstName: 'Florence',
-    lastName: 'Nightingale'
+    lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing']
};

// good - 有尾随逗号的 git 差异
const hero = {
     firstName: 'Florence',
     lastName: 'Nightingale',
+    inventorOf: ['coxcomb chart', 'modern nursing'],
};

如果属性/方法是一个 boolean 值,使用 isVal() 或者 hasVal()。

// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}

可以创建 get() 和 set() 方法,但是要保证一致性。

class Jedi {
  constructor(options = {}) {
    const lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}

不要保存 this 的引用,使用箭头函数或者 函数#bind

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

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

// good
function foo() {
  return () => {
    console.log(this);
  };
}