第一次看到类似 this 的东西在 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 中是否有此类函数声明的技术名称?
这一行是如何将所有这些(使用带有字符串常量的方括号声明的函数)放入 FunMap 对象的属性函数中的?
const map = this;
javascript 类中的方括号符号 []
是否引用类本身?
最佳答案
类中带方括号的语法叫做computed property name .计算方括号内的表达式,并将结果的字符串值用作键。
方括号内的代码无法访问类本身,因为它是在类声明之前求值的。
您的示例创建了一个如下所示的类:
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 的一部分。
关于javascript - 方括号中的函数声明在 Node.js/Javascript 中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059085/