How to pass parameters / arguments from one javascript snippet to another, when evaluated

北战南征 提交于 2019-12-11 08:34:32

问题


My goal is to execute a javascript snippet using another javascript snippet using

new Function(x1, x2, x3, functionBody) call.

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

Edit: 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.


回答1:


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)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function#Specifying_arguments_with_the_Function_constructor

// 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


来源:https://stackoverflow.com/questions/32045695/how-to-pass-parameters-arguments-from-one-javascript-snippet-to-another-when

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!