ES6 Computed (dynamic) property names [duplicate]

2019-07-26 07:11发布

问题:

This question already has an answer here:

  • What's the meaning of “=>” (an arrow formed from equals & greater than) in JavaScript? 12 answers

I am reading this explanation in order to get a better understanding of ES6.

In the bit about Enhanced Object Literals, this is given as example code:

var obj = {
    ... (removed as not relevant) ...

    // Computed (dynamic) property names
    [ 'prop_' + (() => 42)() ]: 42
};

I understand what is happening except for the last sentence

I get that

: 42

Is the value (Number) that will be given to the property, and that

[ 'prop_' + ... ]

Is a dynamic variable name that starts with the string prop_.

However, what does this mean/do?

(() => 42)()

回答1:

(() => 42)() is a long way of writing 42 in ES6 using an arrow function.