javascript - 当名称为字符串时,在类中调用静态 JavaScript 函数
问题描述
我可以动态调用名称为字符串的静态函数吗?经过一番尝试,这就是我所能得到的:
class Test{
static Instance(){
console.log( "Instantiated" );
};
};
Test.Instance();//<-- ok
var testVar = "Test";
eval( testVar + ".Instance()" ); // ok but eval is evil!
window[testVar].Instance();//<-- undefined is not an object (evaluating 'window[testVar].Instance')
解决方案
你可以使用new Function
堆栈片段
class Test {
static Instance() {
console.log("Instantiated");
};
};
var testVar = "Test";
var func = function(string) {
return (new Function('return (' + string + ').Instance()')());
}
func(testVar);
这是一些关于new Function
比较的阅读eval
推荐阅读
- python - PyAutoGui 可以在我的电脑后台运行吗
- office365 - 如何使用onenote api重命名onenote中的部分
- java - 序列化(或解析)一个 Protobuf 对象
- typo3 - Typo3 版本 8.x 异常“未找到连接池”
- sql-server - Sql Server 语言设置 - 在视图中保留英国日期设置
- java - 是否有一个 Java XML 到 JSON 库来生成没有属性的输出 JSON,其中输入 XML 具有 xsi:nil="true"
- xml - 转换为 CSV 时在 XML 节点中保留 HTML 格式
- c++ - MQTT 客户端 - 默认消息处理程序
- hash - 更改文件的 sha1 哈希
- sql-server - 无法访问 SQL Server 实例