【问题标题】:Unfamiliar with this javascript syntax that I came across [duplicate]不熟悉我遇到的这种javascript语法[重复]
【发布时间】:2017-01-28 12:54:17
【问题描述】:

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

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;

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

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

【问题讨论】:

  • 看起来它正在尝试使用来自事件对象的名称定义 2 个函数

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

这样你就可以使用变量作为属性名:

例如:

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]();

【讨论】:

    【解决方案2】:

    这称为计算属性名称。见http://es6-features.org/#ComputedPropertyNames

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-19
      相关资源
      最近更新 更多