Node.js / Javascript 中方括号的函数声明如何工作?

How does function declaration by square brackets work in Node.js / Javascript?

第一次在 Node.js 中看到类似 this 的声明函数。 简而言之,代码类似于此

'use strict';
const Actions = {
  ONE: 'one',
  TWO: 'two',
  THREE: 'three'
};
class FunMap {

  run(action) {
    const map = this;
    map[action]();
  }

  [Actions.ONE] () {
    console.log("Performing action one");
  }

  [Actions.TWO] () {
    console.log("Performing action two");
  }

  [Actions.THREE] () {
    console.log("Performing action three");
  }

}

var funMap = new FunMap();
funMap.run('one');
funMap.run('two');
funMap.run('three');

以上程序会打印

Performing action one
Performing action two
Performing action three

Node.js / Javascript 中是否有此类函数声明的技术名称?

这一行是如何将所有这些(用方括号和字符串常量声明的函数)放入FunMap对象的属性函数中的?

const map = this;

javascript class 中的方括号符号 [] 是否引用 class 本身?

class中带方括号的语法称为computed property name。计算方括号内的表达式,并将结果的字符串值用作键。

方括号内的代码无法访问 class 本身,因为它在 class 声明 之前 求值。

您的示例创建了一个如下所示的 class:

class FunMap {

  run(action) {
    const map = this;
    map[action]();
  }

  one () {
    console.log("Performing action one");
  }

  two () {
    console.log("Performing action two");
  }

  three () {
    console.log("Performing action three");
  }

}

run 函数以不同的方式使用方括号 - 按名称查找 属性。 const map = this 行没有做任何特别的事情——函数会像这样做同样的事情:

run(action) {
  return this[action]();
}

this[action] 表示 "get the property called action of this"。然后将该值作为不带参数的函数调用。

计算 属性 名称已添加到 ES2015 中。通过名称获取对象的下标语法从一开始就是 JavaScript 的一部分。