2

i have the following in JS:

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

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

now, I want to invoke the function that is in 'c'.

Does anyone know how to?

thanks in advance.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
kakush
  • 3,334
  • 14
  • 47
  • 68
  • 4
    Where does `c` come from? Having code in strings is generally a sign of bad design. – Felix Kling Dec 27 '11 at 12:52
  • 1
    possible duplicate of [Given a string describing a Javascript function, convert it to a Javascript function](http://stackoverflow.com/questions/2573548/given-a-string-describing-a-javascript-function-convert-it-to-a-javascript-func) – Felix Kling Dec 27 '11 at 12:54

6 Answers6

2

By either:

 var fn = new Function( "myRequest, myResponse" , "myResponse.body = 'hello';myResponse.end();" );  

or by eval function which executes code directly from string:

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

    fn();
abuduba
  • 4,986
  • 7
  • 26
  • 43
0

That's what eval is for.

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

Be careful though as it's not safe for unverified input, ie if it's not from trusted source it can be dangerous.

soulcheck
  • 36,297
  • 6
  • 91
  • 90
0
<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>

Refer Link:- http://www.w3schools.com/jsref/jsref_eval.asp

Ashish Agarwal
  • 6,215
  • 12
  • 58
  • 91
0

Use the eval function, if you really need to do this.

http://www.w3schools.com/jsref/jsref_eval.asp

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
ynka
  • 1,457
  • 1
  • 11
  • 27
0
//Create the function call from function name and parameter.
var funcCall = strFun + "('" + strParam + "');";

//Call the function
var ret = eval(funcCall);
Salaros
  • 1,444
  • 1
  • 14
  • 34
0

Why not create a function like in next code:

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

Or if you cannot, do next for example:

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();
Andrew D.
  • 8,130
  • 3
  • 21
  • 23