Airbnb JavaScript代码规范(二)

8.箭头函数

1) 当你需要用到匿名(anonynous)函数的时候,使用箭头函数。eslint:prefer-arrow-callback,arrow-saocing

它创建了一个在其上下文中执行的函数版本,这通常是您想要的,并且是一种更简洁的语法。如果你有一个相当复杂的函数,你可能会将这个逻辑移到它自己的命名函数表达式

//bad
[1,2,3].map(function k(x) {
 const y = x+1;
 return x*y;
});
//good
[1,2,3].map((x) => {
 cosnt y = x+1return x*y;
});

2)如果函数体由一个返回无副作用的表达式的单个语句组成,则省略大括号并使用隐式返回。否则,保留大括号并使用返回语句。

// bad
[1, 2, 3].map(number => {
  const nextNumber = number + 1;
  `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map(number => `A string containing the ${number}.`);

// good
[1, 2, 3].map((number) => {
  const nextNumber = number + 1;
  return `A string containing the ${nextNumber}.`;
});

// good
[1, 2, 3].map((number, index) => ({
  [index]: number,
}));

// No implicit return with side effects
function foo(callback) {
  const val = callback();
  if (val === true) {
    // Do something if callback returns true
  }
}

let bool = false;

// bad
foo(() => bool = true);

// good
foo(() => {
  bool = true;
});

3)如果表达式跨越多行,请将其包装在括号中以提高可读性。

// bad
['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  )
);

// good
['get', 'post', 'put'].map(httpMethod => (
  Object.prototype.hasOwnProperty.call(
    httpMagicObjectWithAVeryLongName,
    httpMethod,
  )
));

4) 如果你的函数只有一个参数,并且不使用大括号,则省略括号。否则,为了清晰和一致,总是在参数周围加括号。注意:始终使用括号也是可以接受的,在这种情况下,eslint使用“always”选项。

//bad
[1,2,3].map((x) => x * x);
//good
[1,2,3].map(x => x * x);
//good
[1,2,3].map(number => (
 `A long string with the ${number}.It's so long that we don't want it to take up space on the .map line!`
));
//bad
[1,2,3].map(x => {
 const y = x + 1;
 return x * y;
});
//good
[].map((x) => {
 const y = x + 1;
 return x * y;
});

5)避免使用比较运算符(<=,> =)混淆箭头函数语法(=>)。

//bad
const itemHeight = item => item.height >256 ? item.largeSize : item.smallSize;
//good (1) 跟箭头分行显示,避免混淆
const itemHeigth = (item) => {
 const { heigth,largeSize,smallSize } = item;
 return height > 256 ? largeSize : smallSize;
}
//good (2) 用括号包装起来
const itemHeight = item => (item.height> 256 ? item.largeSize : item.smallSize);

6)使用隐式返回来强化箭头函数体的位置。.

//bad
(foo) => 
 bar;

(foo) => 
 (bar);

//good
(foo) => bar;
(foo) => (bar);
(foo) => (
 bar
);

9.类classes和构造函数Constructors

1) 总是使用class,避免直接操作prototype

猜你喜欢

转载自blog.csdn.net/e_li_na/article/details/80341551