[英]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()
. 我正在使用
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. 我正在从JSON文件读取字符串。
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 使用
arg1
创建新函数,然后通过传递此参数来调用Hosting.Click()
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.