如何将动态依赖项加载到 eval()
调用中? (如果可能的话)
我正在尝试使用多个函数运行对 eval()
的调用,但我似乎无法让它工作。即:
function foo() {
return bar;
}
function foo2() {
return foo();
}
理想情况下,我想做的是:
eval("
(function() {
function foo() {
return bar;
}
return foo();
}())
");
但我不断收到错误消息,提示 foo is not defined
。
我知道如果 foo()
定义在我页面的 html 中,那么我可以使用 eval()
编写一个基本上是 的函数foo2()
得到我想要的结果:
eval("
(function() {
return foo();
}())
");
但我希望能够更改这两个函数并且仍然能够调用 foo2()
,它总是引用 foo()
。这可能吗?我可以通过哪些方式使它正常工作?
最佳答案
尝试在文本区域中输入:
function hello(name) {
alert("hello" + name);
}
那么 func
将是对 hello
的引用(func == hello
)。然后,您可以使用 func
来测试测试用例,例如 hello
。
var ta = document.getElementById("code");
function run() {
var code = "(function() { return " + ta.value + "; })()"; // code that will return a reference to the function typed by the user
var func = eval(code); // func will be the function the user typed in the textarea
func("me"); // you can call it like you want
}
<textarea id="code"></textarea>
<button onclick="run()">Run</button>
关于javascript - 将 JavaScript 的 eval() 与多个依赖函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42309058/