箭头函数
8.1 当你必须要使用匿名函数的时候(比如需要传递一个行内回调函数的时候),使用箭头函数表示法
eslit: prefer-arrow-callback, arrow-spacing jscs: requireArrowFunctions
为什么?因为箭头函数创造了新的一个
this
上下文执行环境,通常情况下都能满足你的需求,而且这样的写法更为简洁。 为什么不?如果你有一个非常复杂的函数,你应该把这些逻辑移出去放大一个命名函数里
// bad
[1, 2, 3].map(function (x) {
const y = x + 1;
return x * y;
});
// good
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
8.2 如果一个函数适合用一行写出并且返回的是一个没有副作用的表达式,那就把花括号、圆括号和 return 都省略掉。如果不是,那就不要省略。
为什么?语法糖。在链式调用中可读性很高
// 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;
});
8.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,
)
));
8.4 如果你的函数只有一个参数而且不使用大括号,则可以省略括号。否则,通常在参数两边加上括号以保持更好的清晰性和一致性。
注意:一直使用括号也是可以接受的,在这种情况下,对eslint使用"always"选项,或者jscs不包含disallowParenthesesAroundArrowParam eslint: arrow-parens jscs: disallowParenthesesAroundArrowParam
为什么?减少视觉混乱
// 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
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
8.5 避免把箭头函数语法(=>
)和比较运算符(<=
,>=
)混淆
eslint: no-confusing-arrow
// bad
const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize;
// bad
const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize;
// good
const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize);
// good
const itemHeight = (item) => {
const { height, largeSize, smallSize } = item;
return height > 256 ? largeSize : smallSize;
};