将函数语句转换为箭头函数不起作用

时间:2017-11-15 15:07:54

标签: javascript ecmascript-6

我正在努力理解以下内容。

我有以下代码:

const myFunction = function (error) {
  console.error(error)
  callSomething();
}

如您所见,我正在使用一个名为callSomething()的函数,但是只要我使用箭头函数然后callSomething()

const myFunction = error => console.error(error);callSomething();

然后不调用callSomething()

1 个答案:

答案 0 :(得分:0)

来自文档

省略花括号意味着将表达式用作MDN documentations says

  

基本语法

(param1, param2, …, paramN) => { statements } (param1, param2, …,
paramN) => expression // equivalent to: (param1, param2, …, paramN) =>
{ return expression; }

// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements } singleParam => { statements }
singleParam => expression

// The parameter list for a function with no parameters should be
written with a pair of parentheses. () => { statements }

Expressions versus statements in Javascript

说明

所以基本上以下内容应该有效,因为callSomething()是一个表达式

const myFunction = error => callSomething(error)

如果语句不是表达式(例如,例如多个表达式),花括号是强制性的

示例1

const myFunction = error => {
  // other statements such as
  console.error(error);
  callSomehting(error);
});

示例2

throw error是一个陈述,但不是表达!

const myFunction = error => {
  throw error;
});