给我,我已经在JS以下功能:如何调用由字符串
var rs = new myResponse();
var rq = new myRequest();
c = "function(myRequest,myResponse){myResponse.body = 'hello'; myResponse.end();}";
现在,我想要调用是在“C”的功能。
有谁知道如何?
在此先感谢。
给我,我已经在JS以下功能:如何调用由字符串
var rs = new myResponse();
var rq = new myRequest();
c = "function(myRequest,myResponse){myResponse.body = 'hello'; myResponse.end();}";
现在,我想要调用是在“C”的功能。
有谁知道如何?
在此先感谢。
有两种方法:
var fn = new Function("myRequest, myResponse" , "myResponse.body = 'hello';myResponse.end();");
或eval
功能,直接从字符串执行代码:
c = "function(myRequest,myResponse){myResponse.body = 'hello'; myResponse.end();}";
eval("var fn = "+c);
fn();
这就是eval的用途。
eval('func = ' + c);
var result = func(rs, rq);
要小心,因为它是不安全的未经验证的输入,即如果它不是来自可靠的来源,它可能是危险的。
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)");
document.write("<br />" + eval("2+2"));
document.write("<br />" + eval(x+17));
</script>
使用eval
功能,如果你真的需要做到这一点。
//Create the function call from function name and parameter.
var funcCall = strFun + "('" + strParam + "');";
//Call the function
var ret = eval(funcCall);
为什么不创建像下面的代码的函数:
var rs = new myResponse();
var rq = new myRequest();
c = new Function("myRequest","myResponse","myResponse.body = 'hello'; myResponse.end();");
// or
// c = new Function("myRequest,myResponse","myResponse.body = 'hello'; myResponse.end();");
c();
或者,如果你不能,下一步例如:
function stringToFunction(str) {
var m=str.match(/\s*function\((.*?)\)\s*{(.*?)}\s*/);
if(m)return new Function(m[1],m[2]);
}
var rs = new myResponse();
var rq = new myRequest();
c = "function(myRequest,myResponse){myResponse.body = 'hello'; myResponse.end();}";
stringToFunction(c)();
// or
//var f=stringToFunction(c);
//f();
哪里'C'从何而来?在字符串中编写代码通常是设计不好的标志。 – 2011-12-27 12:52:37
[给定描述Javascript函数的字符串,将其转换为Javascript函数]的可能重复(http://stackoverflow.com/questions/2573548/given-a-string-describing-a-javascript-function-convert-it -to-A-JavaScript的FUNC) – 2011-12-27 12:54:32