【问题标题】:Why is that code inside => { } needs a return and the content inside => doesn't?为什么 => { } 里面的代码需要返回,而 => 里面的内容不需要?
【发布时间】:2016-01-23 14:45:08
【问题描述】:

我对 Ecmascript 6 比较陌生。最近,我有了一个发现。我可以打开这个 fetch 函数:

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 版本?

【问题讨论】:

  • 因为这是规范。任何关于箭头函数的讨论都将涵盖这一点。从 MDN 页面:箭头函数可以具有“简洁主体”或通常的“块主体”。块体形式不会自动返回值。您需要使用明确的返回声明。如果您要问为什么这是规范,则必须询问委员会成员或查看他们的审议记录。

标签: javascript ecmascript-6


【解决方案1】:

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

  1. 你不需要创建函数体

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

JavaScript 版本是什么?

ECMAScript 6 是 JavaScript。如果您想要求 ECMAScript 5 等效项,那么没有等效项。


如果有多个表达式,那么

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

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


如果我们查看箭头函数的 ES 6 规范,我们会发现 this section 中的语法

ArrowFunction[In, Yield] :

   ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]

ConciseBody[In] :

   [lookahead ≠ { ] AssignmentExpression[?In]

   { FunctionBody }

正如我们在此处看到的,您可以使用{ FunctionBody } 表单或AssignmentExpression 表单(您没有{})。但是如果你使用FunctionBody形式,你需要显式返回值。

【讨论】:

    【解决方案2】:

    请注意,两者

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

    (result) =>
      result.toJSON()
    

    可以写成:

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

    在 ES5 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 2012-06-03
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多