[英]Typescript/Javascript: Call function by string name
I have a *.ts
file with lots of exported functions like:我有一个
*.ts
文件,其中包含许多导出函数,例如:
export function newItemFoo() {
return {foo: 0, bar: '', baz: true};
}
export function newItemBar() {
return {foo: 0, bar: ''};
}
export function newItemXXX() {
return {xxx: 0};
}
I want to make a "magic method" (in the same *.ts
) that can call one of those methods by name, eg:我想制作一个“魔术方法”(在同一个
*.ts
中),可以按名称调用其中一种方法,例如:
export function magicMethod(name: string) {
const newEmptyFunc = new Function(`return new${name}()`);
return newEmptyFunc();
}
magicMethod('ItemFoo');
but it raise an error但它会引发错误
Error: newItemFoo is not defined
错误:未定义 newItemFoo
It works with eval:它适用于评估:
export function magicMethod(name: string) {
return eval(`newEmpty${name}()`);
}
magicMethod('ItemFoo');
How do I call a function by string name with new Function()
?如何使用
new Function()
通过字符串名称调用 function ?
Both using eval()
and new Function()
are convoluted ways to achieve the goal.使用
eval()
和new Function()
都是实现目标的复杂方法。
Try a simpler approach.尝试更简单的方法。 Create an object that provides a mapping between the values you want to pass to
magicMethod()
and the functions to be called.创建一个 object,它提供了要传递给
magicMethod()
的值和要调用的函数之间的映射。 Then implement magicMethod()
this way:然后以这种方式实现
magicMethod()
:
function newItemFoo() {
return {foo: 0, bar: '', baz: true};
}
function newItemBar() {
return {foo: 0, bar: ''};
}
function newItemXXX() {
return {xxx: 0};
}
const magicWand: { [K: string]: Function } = {
Foo: newItemFoo,
Bar: newItemBar,
xxx: newItemXXX, // this allows you to use a different value for the argument
yyy: newItemXXX, // ... to use multiple names for the same function
// ... and to handle gracefully the calls of non-existing functions
};
export function magicMethod(name: string) {
if (magicWand[name]) {
return magicWand[name]();
}
throw new Error(`Method '${name}' is not implemented.`);
}
Usage:用法:
magicMethod('Foo')
// { foo: 0, bar: '', baz: true }
magicMethod('Bar')
// { foo: 0, bar: '' }
magicMethod('xxx')
// { xxx: 0 }
magicMethod('yyy')
// { xxx: 0 }
magicMethod('zzz')
// Error: Method 'zzz' is not implemented.
However, if you provide such a mechanism to invoke the functions defined by the module you probably don't want to make them public using the standard export
mechanism but only though magicMethod()
.但是,如果您提供这样的机制来调用模块定义的函数,您可能不想使用标准
export
机制将它们公开,而只能使用magicMethod()
。 It is the only function that needs to be export
-ed.它是唯一需要
export
的 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.