Functions inside objects

Modern ES6 Approach

You no longer need to specify the function keyword when defining functions inside objects.

First option with named functions:

const myObj = {
  myMethod(params) {
    // ...do something here
  },
  myOtherMethod(params) {
    // ...do something here
  },
  nestedObj: {
    myNestedMethod(params) {
      // ...do something here
    }
  }
};

Second option with anonymous functions:

const myObj = {
  myMethod: (params) => {
    // ...do something here
  },
  myOtherMethod: (params) => {
    // ...do something here
  },
  nestedObj: {
    myNestedMethod: (params) => {
      // ...do something here
    }
  }
};

Pre ES6 style:

const myObj = {
  myMethod: function myMethod(params) {
    // ...do something here
  },
  myOtherMethod: function myOtherMethod(params) {
    // ...do something here
  },
  nestedObj: {
    myNestedMethod: function myNestedMethod(params) {
      // ...do something here
    }
  }
}; 

Note: In the first example the functions are named and have their own this-context. In the second example, the this-context from outside of the functions is used. In the third example, the functions are not named, but have their own this-context.

So while all methods seem similar, they are a bit different.


you need to define the objects like this :

var argument1 = {
    myvar : "12",
    mymethod : function(test) { return something; }
}

then call mymethod like:

argument1.mymethod(parameter);

or the deeper version :

var argument1 = {
    argument2 : {
       mymethod : function(test) { return something; }
    }
} 

then:

argument1.argument2.mymethod(parameter);