# 箭头函数
- 8.1 当你一定要用函数表达式(在回调函数里)的时候就用箭头表达式吧。 eslint: - prefer-arrow-callback(opens new window),- arrow-spacing(opens new window)- Why? 他创建了一个 - this的当前执行上下文的函数的版本,这通常就是你想要的;而且箭头函数是更简洁的语法- Why? 什么时候不用箭头函数: 如果你有一个相当复杂的函数,你可能会把这个逻辑移出到他自己的函数声明里。 - // 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 如果函数体由一个没有副作用的表达式 (opens new window)语句组成,删除大括号和return。否则,继续用大括号和 - return语句。 eslint:- arrow-parens(opens new window),- arrow-body-style(opens new window)- Why? 语法糖,当多个函数链在一起的时候好读 - // 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 })); // 表达式有副作用就不要用隐式return function foo(callback) { const val = callback(); if (val === true) { // Do something if callback returns true } } let bool = false; // bad // 这种情况会return bool = true, 不好 foo(() => bool = true); // good foo(() => { bool = true; });
- 8.3 万一表达式涉及多行,把他包裹在圆括号里更可读。 - Why? 这样清晰的显示函数的开始和结束 - // 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: - arrow-parens(opens new window)- Why? 这样少一些混乱, 其实没啥语法上的讲究,就保持一个风格。 - // bad [1, 2, 3].map(x => x * x); // good [1, 2, 3].map((x) => x * x);
- 8.5 避免箭头函数( - =>)和比较操作符(- <=, >=)混淆. eslint:- no-confusing-arrow(opens new window)- // 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; };
- 8.6 在隐式return中强制约束函数体的位置, 就写在箭头后面。 eslint: - implicit-arrow-linebreak(opens new window)- // bad (foo) => bar; (foo) => (bar); // good (foo) => bar; (foo) => (bar); (foo) => ( bar )
