【发布时间】:2020-01-16 10:59:23
【问题描述】:
我正在尝试将字符串用作函数的一部分。
const import1 = require('./import1');
const import2 = require('./import2');
//on above files there is a method, let's call it method1.
const string = "import1"; // or could be "import2"
//I would like to use above string as code.
//This is what I tried:
const functionToUse = new Function(string + ".method1()");
functionToUse();
这是我得到的错误:“ReferenceError: import1 is not defined”
我检查了这个答案:Convert a string to a function, gives ReferenceError,它有点工作,但我需要将 import1 或 2 作为字符串传递。
非常感谢所有帮助!
【问题讨论】:
-
代替
new Function,创建一个FunctionMap,然后使用key访问 -
问题是,您正在尝试创建一个类似的函数:
new Function('obj.method1()')并且这样的属性不存在。快速破解将使用eval,但不建议这样做。而是做const fnMap = { import1, import2 }; const obj = fnMap[string]; obj.method1(); -
与几乎所有“如何将字符串转换为变量”问题一样,与之相对的是“您必须避免使用对象的具体原因是什么?”
-
@Rajesh 这真是太神奇了,我没想到这一点。非常感谢!!!您能否为此创建一个答案,然后我可以接受。
标签: javascript node.js function