Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ES6 object method assignment: a, 'a', and ['a']?

With ES6, I can create a new object with functions like the following:

var obj = {
    something() {}
};

That makes sense. But I can also do this:

var obj = {
    'something'() {}
};

Or I can do this:

var obj = {
    ['something']() {}
};

Is there a difference between these three syntaxes? Why are all of these syntactically valid?

like image 230
apscience Avatar asked Feb 08 '23 14:02

apscience


2 Answers

Is there a difference between these three syntaxes?

Not wrt to the results in your example.

However, the different syntaxes do have different characteristics. The way the property name is defined is not specific to method definitions btw, the rules apply to all property names:

  • Property names that are valid identifier names or number literals don't need to be quoted:

    {
      foo: ...,
      10e4: ...,
      if: ...,
    }
    
  • Anything else needs to be quoted:

    {
      'foo+bar': ...,
      'abc def': ...,
      '123,45': ...,
    }
    
  • The square bracket syntax is new in ES6 and allows you do dynamically compute property names:

    {
       [getPropertyName()]: ...,
       ['item' + (i * 3)]: ...,
    }
    

Why are all of these syntactically valid?

Because the grammar allows it:

MethodDefinition :
    PropertyName ( StrictFormalParameters ) { FunctionBody }
    GeneratorMethod
    get PropertyName ( ) { FunctionBody }
    set PropertyName( PropertySetParameterList ) { FunctionBody }

PropertyName :
    LiteralPropertyName
    ComputedPropertyName

LiteralPropertyName :
    IdentifierName
    StringLiteral
    NumericLiteral

ComputedPropertyName :
    [ AssignmentExpression ]

(not sure what kind of answer you expect here)

If you consider methods to be equivalent to assigning a function to the property, it seems to make sense to apply the same rules for property names to function/method names.

like image 183
Felix Kling Avatar answered Feb 10 '23 02:02

Felix Kling


First and second are the same, and do the same as

obj.something = function something() {}

the third one creates an anonymous function and stores it in obj.something. It's an equivalent to this:

obj['something'] = function() {}

Quotes allow to create keys (and hence function names) that are not valid identifiers in JS, for example:

 var obj = {
    '123'() {}
};

creates a function with the name 123, believe it or not.

The square brackets syntax allows arbitrary expressions, so you can do

 var obj = {
   ['myfunc_' + getFuncName()] () {}
 }

and similar cool things.

like image 43
georg Avatar answered Feb 10 '23 02:02

georg