开发者

Passing javascript to a function

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开发者_StackOverflow中文版) {
// 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?


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

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

function bar(fn){
fn();
}

bar(foo); // alerts 'foo'


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?


eval() is what you may want.


You can use eval() for this.


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.
}


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


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.


You can do:

function test(js) {
  setTimeout(js, 1000); //Execute in 1 second
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜