2011-12-27 63 views
2

给我,我已经在JS以下功能:如何调用由字符串

var rs = new myResponse(); 
var rq = new myRequest(); 

c = "function(myRequest,myResponse){myResponse.body = 'hello'; myResponse.end();}"; 

现在,我想要调用是在“C”的功能。

有谁知道如何?

在此先感谢。

+4

哪里'C'从何而来?在字符串中编写代码通常是设计不好的标志。 – 2011-12-27 12:52:37

+1

[给定描述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

回答

2

有两种方法:

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(); 
0

这就是eval的用途。

eval('func = ' + c); 
var result = func(rs, rq); 

要小心,因为它是不安全的未经验证的输入,即如果它不是来自可靠的来源,它可能是危险的。

0
//Create the function call from function name and parameter. 
var funcCall = strFun + "('" + strParam + "');"; 

//Call the function 
var ret = eval(funcCall); 
0

为什么不创建像下面的代码的函数:

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();