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.

2

6 Answers 6

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();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

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

Comments

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.

Comments

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

Comments

0

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.