简体   繁体   中英

Passing arguments to a function which is created using the new function keyword in javascript

I am converting a string to function expression using new Function() .

It is working fine, but I need to pass arguments to the function. How to do that?

I am reading the string from a JSON file.

var act = new Function("Hosting.Click()");
act();

Assuming there is really no better way to do this .

You would need to parse the string which contains the code, and substitute arguments in there.

For example, if the pattern was always a method call, you could split it on the parenthesis, and join arguments inside. However, if it was always a function call, you'd be better off splitting out the parts and calling the function directly (will give you a chance to ensure the string is what you're expecting).

Try this-

creating new Function with arg1 and then calling Hosting.Click() by passing this argument

 var Hosting={Click:function(){ alert(JSON.stringify(arguments)); }} var act = new Function("arg1","Hosting.Click(arg1)"); act("Value for argument 1"); 

Update :-

For any no of arguments -

var act2 = new Function("Hosting.Click.apply(window,arguments)");
act2("any no of arguments",1,2,3,4,5,"Hi");

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM