简体   繁体   English

为什么在此函数中大括号之外有括号,这意味着什么?

[英]Why are there brackets outside of the curly brackets in this function and what does this mean?

I came across the following code in a GraphQL-related post . 我在GraphQL相关的文章中遇到了以下代码。 Why are there brackets outside of the curly brackets in the fields parameter and what does this mean? 为什么在fields参数的花括号之外有括号,这是什么意思?

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => ({
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  })
});

The following are the function expressions / declarations that I am aware of: 以下是我知道的函数表达式/声明:

Standard Named Functions 标准命名函数

function sayHello() {
    alert("hello!");
};

ES6 Anonymous Functions ES6匿名函数

() => {
    alert("hello!");
};

Self Invoked Functions 自调用功能

(function sayHello() {
    alert("hello!");
})();

Self Invoked ES6 Anonymous Functions 自调用ES6匿名函数

(() => {
    alert("hello!");
})();

As far as I'm aware, the fields function does not fit any of the above. 据我所知,fields函数不适合以上任何一个。

The parenthesis are there to make the function return the object without having to wrap the entire object in braces with a return . 括号可以使函数返回对象,而不必用return大括号括起来。

For example this doesn't work: 例如,这不起作用

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => {                  // interpreted as a block not an object
    name: { type: GraphQLString },
    bestFriend: { type: PersonType },
  }
});

because the {} would be interpreted as a block, when you want to return an object. 因为当您要返回一个对象时, {}将被解释为一个块。

You could do this: 您可以这样做:

var PersonType = new GraphQLObjectType({
  name: 'Person',
  fields: () => {
    return { name: { type: GraphQLString },
             bestFriend: { type: PersonType },
           }
  }
});

but that doesn't seem as nice as just using the parenthesis which will cause the function to return the object. 但这似乎不如仅使用括号使函数返回该对象好。

返回的对象包含在“()”括号中,因此花括号不被视为函数体,而是对象。

If the parentheses weren't there, what would it look like? 如果没有括号,它将是什么样?

fields: () => {
  name: { type: GraphQLString },
  bestFriend: { type: PersonType },
}

Well that looks an awful lot like function block syntax. 好吧,看起来很像功能块语法。 And in fact, that's what interpreters will assume, and then throw syntax errors when they see weird key: value syntax where standard expressions are expected. 实际上,这就是解释器所假定的,然后当他们看到奇怪的key: value时抛出语法错误key: value期望标准表达式的key: value语法。

In other words, the parentheses are there to indicate that the function returns an object, and that the curly braces should not be interpreted as enclosing a code block. 换句话说,括号在这里表示函数返回一个对象,并且花括号不应该解释为包​​含代码块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM