ES6 粗箭头和括号 `(...) =>({...})` [英] ES6 Fat Arrow and Parentheses `(...) => ({...})`

查看:26
本文介绍了ES6 粗箭头和括号 `(...) =>({...})`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究一些 Graph QL/React/Relay 示例,但遇到了一些奇怪的语法.

I've been working through some Graph QL/React/Relay examples and I ran into some strange syntax.

在 Graph QL Objects 中定义字段时,使用以下语法:

When defining the fields in Graph QL Objects the following syntax is used:

const xType = new GraphQLObjectType({
  name: 'X',
  description: 'A made up type for example.',
  fields: () => ({
    field: {/*etc.*/}
  })
});

据我所知,这只是定义一个匿名函数并将其分配给 xType.fields.该匿名函数返回包含字段定义的对象.

From what I gather this is just defining an anonymous function and assigning it to xType.fields. That anonymous function returns the object containing the field definitions.

我假设 Graph QL 模式机制的工作原理必须定义为返回对象的函数,而不是简单的对象.但让我困惑的部分是花括号周围的括号.

I'm assuming with however the Graph QL schema mechanism works this has to be defined as a function returning an object rather than simply an object. But the part that has me confused is the parenthesis around the curly braces.

这是为了区分对象定义和函数定义吗?是为了读者清楚起见吗?

Is this to differentiate an object definition from a function definition? Is it for clarity's sake for the reader?

谷歌搜索发现的唯一类似语法是在 airbnb 风格指南中,它似乎是一个可读性/清晰度的东西.

The only similar syntax a google search has found is in the airbnb style guide where it seems to be a readability/clarity thing.

当我开始更多地使用 Graph QL 时,只是在寻找超出我假设的确认或解释.

Just looking for confirmation or an explanation beyond my assumptions as I start to play around with Graph QL a little more.

推荐答案

fields: () => ({
  field: {/*etc.*/}
})

是一个隐式返回对象(文字)的函数.不使用 () JavaScript 解释器将 {} 解释为函数体的包装器,而不是一个对象.

is a function that implicitly returns an object (literal). Without using () JavaScript interpreter interprets the {} as a wrapper for the function body and not as an object.

不使用括号:()field: ... 语句被视为label 语句,函数返回未定义.等效的语法是:

Without using parens: (), the field: ... statement is treated as a label statement and the function returns undefined. The equivalent syntax is:

fields: () => { // start of the function body
   // now we have to define an object 
   // and explicitly use the return keyword
   return { field: {/*etc.*/} }
}

所以为了清楚起见,父母不在那里.它用于使用箭头函数的隐式返回特性.

So parents are not there for clarity. It's there for using implicit-returning feature of arrow functions.

这篇关于ES6 粗箭头和括号 `(...) =>({...})`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆