Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 705
Andy Avatar asked Feb 05 '23 23:02

Andy


1 Answers

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

like image 107
Peter Kota Avatar answered Feb 07 '23 12:02

Peter Kota