【问题标题】:Why are there brackets outside of the curly brackets in this function and what does this mean?为什么这个函数的大括号外面有括号,这是什么意思?
【发布时间】:2018-09-28 04:20:28
【问题描述】:

我在GraphQL-related post 中发现了以下代码。 为什么fields参数的大括号外面有括号,这是什么意思?

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

以下是我知道的函数表达式/声明:

标准命名函数

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

ES6 匿名函数

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

自调用函数

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

自调用 ES6 匿名函数

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

据我所知,字段函数不符合上述任何一项。

【问题讨论】:

  • 阅读the documentation 总是有用的。
  • 啊,明白了。 @Teemu 感谢您的链接。我现在在“高级语法”下看到它。发现将我的问题用文字传达给 Google 有点困难,但现在很明显我应该更深入地研究箭头函数。

标签: javascript function


【解决方案1】:

括号用于使函数返回对象,而不必用 return 将整个对象包裹在大括号中。

例如,这个不起作用

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

因为{} 会被解释为一个块,当您想要返回一个对象时。

你可以这样做:

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

但这似乎不如只使用括号会导致函数返回对象那么好。

【讨论】:

    【解决方案2】:

    返回的对象被包裹在'()'括号中,因此花括号不被视为函数体,而是一个对象。

    【讨论】:

      【解决方案3】:

      如果没有括号,它会是什么样子?

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

      这看起来很像功能块语法。事实上,这就是解释器会假设的内容,然后当他们看到奇怪的 key: value 语法需要标准表达式时抛出语法错误。

      换句话说,括号表示函数返回一个对象,大括号不应被解释为包含代码块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        • 2013-05-28
        相关资源
        最近更新 更多