How is this function stored in my object?

I came across a certain way of placing a function inside a javascript object, which I do not quite understand. Typically, you have something like:

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

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

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

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

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

Is this another way to declare methods?

+4
source share
1 answer

This is an ES2015 function related to the definition of a method.

Starting with ECMAScript 2015, shorter syntax for method definitions on object initializers. This is an abbreviation for the function assigned to the method name.

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

+8
source

Source: https://habr.com/ru/post/1671226/


All Articles