在方括号里的函数声明如何在Node.js / Javascript中工作?
第一次在Node.js中看到像这样的东西来声明函数。 总之,代码与此类似
'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中是否有这种types的函数声明的技术名称?
这条线如何将所有这些( 通过使用方括号中的string常量声明的函数 )放入到FunMap对象的属性函数中?
const map = this;
javascript类中的方括号符号[]
是否引用类本身?
带有方括号的语法称为计算属性名称 。 计算方括号内的expression式,并将结果的string值用作键。
方括号内的代码不能访问类本身,因为它是在类声明之前进行评估的。
你的例子创build一个如下所示的类:
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]
意思是“得到这个属性叫做this
action
”。 然后该值被称为没有参数的函数。
计算的属性名称在ES2015中添加。 从一开始,通过名称获取对象的下标语法就成为了JavaScript的一部分。