2

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?

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 2
    [mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015) - there's proof and explanation in one – Jaromanda X Feb 25 '16 at 08:53

3 Answers3

6

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

Thomas
  • 3,513
  • 1
  • 13
  • 10
2

MDN

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

Syntax

var obj = {
  property( parameters… ) {},
  *generator( parameters… ) {},
// also with computed keys:
  [property]( parameters… ) {},
  *[generator]( parameters… ) {},
// compare ES5 getter/setter syntax:
  get property() {},
  set property(value) {}
};

You are now able to shorten this to:

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

MDN Links to ECMA

BenG
  • 14,826
  • 5
  • 45
  • 60
1
Enhanced Object Literals

Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences.

var obj = {
    // __proto__
    __proto__: theProtoObj,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

Reference : https://github.com/lukehoban/es6features#enhanced-object-literals

Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30