tags:

views:

56

answers:

8

Hello,

Can I pass some Javascript to a function and then execute that Javascript from within the function, e.g.

test("a = 1; b = 2; test2(a,b);");

function test(js) {
// execute dynamically generated JS here.
}

Basically I have some code that is generated on the server and I want to pass that code to a JS function which when it has finished processing it executes the code passed as a parameter.

This could also be useful for the parameter of setTimeout, then the code passed could be executed in the timeout event.

Can this be done?

+2  A: 

It is possible if you do something like this as an example:

function foo(){
alert('foo');
}

function bar(fn){
fn();
}

bar(foo); // alerts 'foo'
Marcos Placona
+1  A: 

eval() is what you may want.

Bertrand Marron
A: 

I think you're looking for eval(), but what you should be looking for is json.

Felix
+3  A: 

You can do this with eval(): http://www.w3schools.com/jsref/jsref_eval.asp

However, be careful that you don't expose yourself to the security issues.

http://stackoverflow.com/questions/86513/why-is-using-javascript-eval-function-a-bad-idea

Mark B
A: 

This is what eval is for:

test("a = 1; b = 2; test2(a,b);"); 

function test(js) { 
    eval(js); 
} 

Cue the onslaught of "eval is evil" comments.

Andy E
+4  A: 

You can use eval() for this.

Arun P Johny
A: 

You can do:

function test(js) {
  setTimeout(js, 1000); //Execute in 1 second
}
Nick Craver
+1  A: 

In stead of using eval, you could create a function from the parameter string like this

test("a = 1; b = 2; test2(a,b);");

function test(js) {
   var fn = new Function(js);
   // execute you new function [fn] here.
}
KooiInc