我不熟悉我遇到的这种javascript语法

Jos*_*egl 4 javascript ecmascript-6 reactjs redux

我刚开始一个新工作,我有一些React代码需要维护,有一个名为authenticationHandlers.jsthis 的文件就是代码在文件中的样子.

const events = require("./authenticationEvents.js");

const authenticationHandlers = {
    [events.Errored.Name](prev, event) {
         const update = {
             UnauthorizedError: event.Error
        };

        return Object.assign({}, prev, update);
    },
    [events.ClearError.Name](prev, event) {
        const update = {
            UnauthorizedError: null
        };

        return Object.assign({}, prev, update);
    }
};

module.exports = authenticationHandlers;
Run Code Online (Sandbox Code Playgroud)

我对代码的功能没有任何疑问,但是括号语法在行[events.Erorred.Name]和行上做了什么[events.ClearError.Name]

换句话说,括号是什么意思?

Nea*_*eal 5

这样您就可以将变量用作属性名称:

例如:

const a = 'banana';
const fnName = 'pudding';

const b = {
    [a]: 42,
    [fnName]() {
        console.log(`I am logging from ${fnName}`);
    }
};

console.log(b); //{banana: 42, pudding: fn}
b[fnName]();
Run Code Online (Sandbox Code Playgroud)