我有一个*.ts包含许多导出功能的文件,例如:
export function newItemFoo() {
return {foo: 0, bar: '', baz: true};
}
export function newItemBar() {
return {foo: 0, bar: ''};
}
export function newItemXXX() {
return {xxx: 0};
}
Run Code Online (Sandbox Code Playgroud)
我想制作一个*.ts可以按名称调用这些方法之一的“魔术方法”(在同一个中),例如:
export function magicMethod(name: string) {
const newEmptyFunc = new Function(`return new${name}()`);
return newEmptyFunc();
}
magicMethod('ItemFoo');
Run Code Online (Sandbox Code Playgroud)
但它引发了一个错误
错误:newItemFoo 未定义
它适用于 eval:
export function magicMethod(name: string) {
return eval(`newEmpty${name}()`);
}
magicMethod('ItemFoo');
Run Code Online (Sandbox Code Playgroud)
如何通过字符串名称调用函数new Function()?