0

我正在关注本教程,

https://dev-blog.apollodata.com/tutorial-building-a-graphql-server-cddaa023c035

但我的问题不是关于阿波罗服务器,它只是使用 javascript 对象的一小部分;我想知道javascript的理论,这个块在对象内部定义了什么:

author(root, args){
  return { id: 1, firstName: 'Hello', lastName: 'World' };
}

前一个块在这个对象中,但我不知道javascript中这个定义的理论,究竟是什么?

const resolvers = {
  Query: {
    author(root, args){
      return { id: 1, firstName: 'Hello', lastName: 'World' };
    },
  },
  Author: {
    posts(author){
      return [
        { id: 1, title: 'A post', text: 'Some text', views: 2},
        { id: 2, title: 'Another post', text: 'Some other text', views: 200}
      ];
    },
  },
  Post: {
    author(post){
      return { id: 1, firstName: 'Hello', lastName: 'World' };
    },
  },
};

export default resolvers;
4

1 回答 1

3

这种语法称为方法定义,它允许您将方法声明为对象的属性,而无需使用箭头或function关键字。

这种速记语法类似于ECMAScript 2015 中引入的getterand语法。setter

速记语法使用命名函数而不是匿名函数。与匿名函数不同,这些命名函数可以从函数体本身调用。

var foo = {
  bar() { // method definition
    return "Hello world !"; 
  }
};

console.log( foo.bar() );

做同样事情的更常用的方法是使用这样的函数

var foo = {
  bar : function() {
    return "Hello world !"; 
  }
};

console.log( foo.bar() );

于 2017-08-28T15:09:39.693 回答