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

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

问题描述

我一直在使用一些图形QL / React / Relay示例,我遇到了一些奇怪的语法。



当在图QL对象中定义字段时,使用语法:

  const xType = new GraphQLObjectType({
name:'X',
description ,
字段:()=>({
字段:{/*etc.*/}
})
}) ;

从我收集到的只是定义一个匿名函数并将其分配给xType.fields。该匿名函数返回包含字段定义的对象。



我假设Graph QL架构机制的作用是将其定义为返回对象而不是简单的对象的函数。但是让我困惑的部分是大括号周围的括号。



这是为了区分对象定义和函数定义吗?为了清楚读者的缘故吗?



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



只需查找确认或解释超出我的假设,我开始玩Graph QL一点点。

解决方案

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

是隐式返回一个对象(文字)的函数。不使用() JavaScript解释器将 {} 解释为函数体的包装器,而不是对象。没有使用括号:()字段:... 语句被视为标签语句,函数返回 undefined 。相当的语法是:

  fields:()=> {//启动函数体
//现在我们必须定义一个对象
//并显式地使用返回关键字
return {field:{/*etc.*/}}
}

所以父母不在场。它是使用箭头函数的隐式返回功能。


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

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.*/}
  })
});

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.

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?

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

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.*/}
})

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

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天全站免登陆