Andy
Andy

Reputation: 117

How does this function get stored in my object?

I came across a particular way of placing a function inside of a javascript object I don't quite understand. Typically, you would have something like:

var obj = {
 foo: function() {
   return 'bar';
  }

} //obj.foo() === 'bar'

However, I found that I can get the same thing with:

var obj = {
  foo() {
   return 'bar';
  }

} //obj.foo() === 'bar'

Is this just another way of declaring methods?

Upvotes: 4

Views: 65

Answers (1)

Peter Kota
Peter Kota

Reputation: 8350

This is an ES2015 feature regarding to Method Definition.

Starting with ECMAScript 2015, a shorter syntax for method definitions on objects initializers is introduced. It is a shorthand for a function assigned to the method's name.

Check this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

Upvotes: 8

Related Questions