Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand for defining function in JavaScript object [duplicate]

Tags:

javascript

Accidentally I written a code like below,

var x = {hai:10,test(){ alert("I am alive")}};
x.test(); //alerting the value

It is working fine and I wonder how this code is working? since it was considered previously as an invalid grammar. And I know, In ECMAscript 6, there is a shorthand for assigning properties has been introduced.

Example:

var x = 5, y = {x};  // is as same as var x=5,y={x:x};

But I am not sure about the function definition. Can anyone explain about it with proof from documentation?

like image 694
Rajaprabhu Aravindasamy Avatar asked Aug 30 '26 22:08

Rajaprabhu Aravindasamy


1 Answers

This is a Feature coming with ES2015. You can skip the function-keyword for method-definitions (not for plain functions).
So { doSth(){/*...*/ } } is simply a shorthand for { doSth: function(){/*...*/ } }

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Method_definitions

like image 75
Thomas Avatar answered Sep 02 '26 15:09

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!