评估时如何将参数/参数从一个 javascript 片段传递到另一个
问题描述:
我的目标是使用
new Function(x1, x2, x3, functionBody)
调用.
当我需要将参数传递给函数时,我的问题出现了,这是因为 functionBody 可能会显示为具有全局声明和调用的新 Js 脚本.
My problem appears when i need to pass parameters to the function, this is because functionBody may appear as a new Js script with global declarations and calls.
function main() {
var a = x1;
var b = x2;
var c = x3;
....
....
}
main(); // this is the function that starts the flow of the secondary Js snippets
我有一个脚本负责下载和执行另一个 Js 脚本.每个下载的脚本都通过对 main() 的全局调用执行,调用者脚本不知道该调用.
I have a script responsible for downloading and executing another Js script. each downloaded script is executed by a global call to main(), which is unknown to the caller script.
答
你似乎误解了 Function
构造函数有效.
You seem to be misunderstanding how the Function
constructor works.
// This does not create a function with x1, x2, x3 parameters
new Function(x1, x2, x3, functionBody)
// This does
new Function('x1', 'x2', 'x3', functionBody)
// Create a function that takes two arguments and returns the sum of those arguments
var adder = new Function('a', 'b', 'return a + b');
// Call the function
adder(2, 6);
// > 8