为什么 => { } 中的代码需要返回,而 => 中的内容不需要

Why is that code inside => { } needs a return and the content inside => doesn't?

本文关键字:不需要 返回 为什么 代码      更新时间:2023-09-26

我对 Ecmascript 6 比较陌生。最近,我有了一个发现。我可以转动这个获取函数:

store.fetchList = () => {
  const Document = Parse.Object.extend('Document')
  const query = new Parse.Query(Document)
  return query.find().then((results) => {
    return _.map(results, (result) => {
      return result.toJSON()
    })
  })
}

进入这个(如果去掉大括号,只需要第一次返回):

store.fetchList = () => {
  const Document = Parse.Object.extend('Document')
  const query = new Parse.Query(Document)
  return query.find().then((results) =>
    _.map(results, (result) =>
      result.toJSON()
    )
  )
}

这是为什么呢?Ecmascript 5 版本是什么?

如果箭头函数只有一个表达式,则

  1. 无需创建函数体

  2. 默认情况下返回该表达式的值。

JavaScript版本是什么?

ECMAScript 6 是 JavaScript。如果你的意思是要求 ECMAScript 5 等价物,那么这个没有等价物。

<小时 />

如果有多个表达式,则

  1. 我们需要将它们包含在 {} 中,基本上我们需要创建一个块(函数体)。

  2. 我们需要显式返回值。

<小时 />

如果我们查看箭头函数的 ES 6 规范,我们会在本节中找到语法

ArrowFunction[In, Yield] :
   ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]
ConciseBody[In] :
   [lookahead ≠ { ] AssignmentExpression[?In]
   { FunctionBody }

正如我们在这里看到的,您可以使用{ FunctionBody }形式,也可以使用AssignmentExpression形式(您没有{})。但是,如果使用FunctionBody窗体,则需要显式返回值。

请注意,两者

(result) => {
  return result.toJSON()
}

(result) =>
  result.toJSON()

将写成:

(function(result) {
    return result.toJSON();
}).bind(this)

在 ES5 中。