缩短箭头函数的方法

1.只有一个入参时候可以省略括号

const greet = (who) => {
  return `${who}, Welcome!`
};
const greet = who => {
  return `${who}, Welcome!`
};

2.参数可以带默认值,但是需要带括号

const greet = (who) => {
  return `${who}, Welcome!`
};
const greet =  (who = 'green')=> {
  return `${who}, Welcome!`
};

3.可以已解构的参数

const greetDestruct = ({ who }) => {
  return `${who}, Welcome!`;
};
const race = {
  planet: 'Jupiter',
  who: 'Jupiterians'
};

greetDestruct(race);

4.当箭头函数主体内仅包含一个表达式时,可以去掉return 关键字

const greetConcise = who => `${who}, Welcome!`;

greetConcise('Friends'); 

5.简洁写法(阅读困难,并不推荐)

const multiplyFactory = m => { 
  return x => x * m;
};

const double = multiplyFactory(2);
double(5); // => 10

const multiplyFactory = m => x => x * m;

const double = multiplyFactory(2);
double(5); // => 10


你可能感兴趣的:(缩短箭头函数的方法)