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

前端 未结 2 1222
梦谈多话
梦谈多话 2021-01-19 23:59

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

var obj = {
    something() {}
};

That makes sense. But I can also d

2条回答
  •  耶瑟儿~
    2021-01-20 00:18

    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.

提交回复
热议问题