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

时间:2018-09-21 15:50:37

标签: javascript reactjs

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

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

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

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

import {hello} from './helper';

我尝试使用eval,window和new Function来调用我的函数,但是没有运气

//getting console error "hello is not defined"

eval('hello()');  

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

var fn = new Function('hello()');
fn();

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

function helloWrapper() {
    hello();
}

eval('helloWrapper()');  

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

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

预先感谢

2 个答案:

答案 0 :(得分:3)

eval("hello()")应该可以正常工作-但这不是您应该这样做的方式。 :-)

相反,构建一个包含以下功能的对象:

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

const functions = {hello, groot/*, ... */};

,然后这样称呼他们:

functions[name]();

Live example on plnkr.co

答案 1 :(得分:1)

通常,按名称引用函数在客户端代码或任何其他可以缩小的代码中都是不安全的。问题中解释的方法仅会起作用,因为data <- structure(list(name = c("aldrinas63_rios200_2001", "sa_c.fr.1234" )), class = "data.frame", row.names = c(NA, -2L)) 不仅是函数名,而且是导入。由于ES模块的工作方式,导入名称将在最小化时保留。

为了使函数名称被引用,它应该是对象属性。如果是导入,则已经有这样的对象,它是模块导出:

hello

如果功能可能来自多个模块,则应该有一个中间模块来重新导出它们。

import * as helper from './helper';

helper['hello']();

来自底层模块的所有功能在导入为export * from './helper'; export * from './another-helper'; 时都可以用作属性:

*
相关问题