通过函数名称的字符串值调用导出函数

Rob*_*b C 2 javascript reactjs

这是我想要实现的一个非常简单的示例,基本上我想通过函数名称的字符串值来调用函数,例如“hello”应该调用 hello()

我有一个 helper.js 文件,其中包含导出的函数,例如

export function hello() {
    console.log('is it me you`re looking for?');
}
Run Code Online (Sandbox Code Playgroud)

我将其导入到另一个js文件中以供使用

import {hello} from './helper';
Run Code Online (Sandbox Code Playgroud)

我尝试过使用 eval、window 和 new Function 来调用我的函数,但没有成功

//getting console error "hello is not defined"

eval('hello()');  

var fn = window['hello()'];
fn();

var fn = new Function('hello()');
fn();
Run Code Online (Sandbox Code Playgroud)

如果我像这样包装函数,则 eval 会触发包装器。

function helloWrapper() {
    hello();
}

eval('helloWrapper()');  
Run Code Online (Sandbox Code Playgroud)

我似乎无法直接触发导出的 hello() 函数。我有大约 10 个需要触发的函数,因此为每个函数都有一个包装器似乎有点老套,我想知道是否有办法实现这一点?

如果有人能指出我正确的方向,任何帮助将不胜感激。

提前致谢

T.J*_*der 5

eval("hello()")应该可以正常工作——但这​​不是你应该这样做的。:-)

相反,构建一个包含以下函数的对象:

import {hello} from './helper'; // In some environments, these need the
import {groot} from './groot';  // .js on the filenames.
// ...

const functions = {hello, groot/*, ... */};
Run Code Online (Sandbox Code Playgroud)

然后这样称呼它们:

functions[name]();
Run Code Online (Sandbox Code Playgroud)

plnkr.co 上的实例