0

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?

AJ.
  • 10,732
  • 13
  • 41
  • 50
  • The answers below work, but how is the server-generated script given to the client? Depending on there may be better ways. – Bart van Heukelom Mar 08 '10 at 12:22
  • 1
    If you are dynamically generating JS on the server then you are probably doing something wrong. Write the JS up front and then pass data from the server. Use the data to determine which functions to run. – Quentin Mar 08 '10 at 12:24

8 Answers8

2

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
  • 21,468
  • 11
  • 68
  • 93
1

eval() is what you may want.

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
1

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.

Why is using the JavaScript eval function a bad idea?

Community
  • 1
  • 1
Mark Bell
  • 28,985
  • 26
  • 118
  • 145
1

You can use eval() for this.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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
  • 119,216
  • 31
  • 141
  • 177
0

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

Felix
  • 88,392
  • 43
  • 149
  • 167
0

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
  • 338,112
  • 86
  • 474
  • 445
0

You can do:

function test(js) {
  setTimeout(js, 1000); //Execute in 1 second
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155