function with parameters inside an object

54 views Asked by At

I'm following this tutorial,

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

but my question is not about apollo server, it's just a small part that use javascript object; i'd like to know the theory of javascript, what is this block define inside an object:

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

previous block is in this object, but i don't know the theory about this definition in javascript, what is exactly?

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;
1

There are 1 answers

0
adeneo On

This syntax is called Method Definitions, it lets you declare methods as properties of an object without using arrows or the function keyword.

This shorthand syntax is similar to the getter and setter syntax also introduced in ECMAScript 2015.

The shorthand syntax uses named functions instead of anonymous functions. These named functions can be called from the function body itself, unlike with anonymous functions.

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

console.log( foo.bar() );

The more usual way to do the same thing, would be with a function like this

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

console.log( foo.bar() );