user823527
user823527

Reputation: 3712

How do I call a function defined in a javascript variable

I have a function defined in a javascript variable. How do I call that function within a javascript function?

function clear_viewer() {
     var stop_function = "jwplayer.stop();";
     // call stop_function here
}

Thanks.

Upvotes: 1

Views: 5966

Answers (3)

SeanCannon
SeanCannon

Reputation: 78046

function clear_viewer() {
     var stop_function = function(){ jwplayer.stop();};
     stop_function();
}

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245499

Could always go with the 'all evil' eval():

eval(stop_function);

Obviously you need to be very careful when using eval so that you don't wind up executing malicious code accidentally. Another option would be to turn stop_function into an anonymous function that executes your code:

var stop_function = function(){
    jwplayer.stop();
};

stop_function();

Upvotes: 1

Alex Wayne
Alex Wayne

Reputation: 187272

function clear_viewer() {
     var stop_function = "jwplayer.stop();";
     eval(stop_function);
}

You shouldn't do this though, eval should be avoided if at all possible. Instead you should do something more like this, which creates a function directly for later execution.

function clear_viewer() {
     var stop_function = function() {
       jwplayer.stop();
     };
     stop_function();
}

Upvotes: 4

Related Questions