2

I have always defined methods in objects like this:

{
  a: function(par1, par2) { },
}

But recently I see this (which I assume is equivalent, but I am not sure):

{
  a(par1, par2) { },
}

When has this syntax been introduced?

blueFast
  • 41,341
  • 63
  • 198
  • 344

3 Answers3

2

What you're referring to is part of the ES6 Extended Object Literal support.

You are correct in assuming that your two examples are functionally equivalent.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

It is ES6 syntax, a shorthand and functionally the same.

MDN - Method definitions

aw04
  • 10,857
  • 10
  • 56
  • 89
1

Yep, this is new ES6 way of doing it

old way

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

new way

usually you can use old syntax, new one is optional but bit shorter

var obj = {
  foo() {},
  bar() {}
};

it better to skip duplication when you do something like that

function method(){};

return {
   method: method
}; 

it may looks like

return {
   method
}; 

same syntax you may find at es6 class definition

class MyClass {
  constructor(geometry, materials) {}
  update(camera) {}

  get boneCount() {}
  set matrixType(matrixType) {}
}

Best regards

Egor

Egor Malkevich
  • 1,516
  • 1
  • 11
  • 24