1

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.

1
  • Why are you storing the function as string, simply call jwplayer().stop()? Commented Feb 2, 2012 at 18:14

3 Answers 3

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

5 Comments

Why suggest eval() and then tell the OP they shouldn't do this?
Because we don't have the full story here. This may be a contrived example, but based on a real world problem where he gets a string of JS from somewhere he can't control, and wants to execute it. If that's the case, eval is the only real option. Note how I said "eval should be avoided if at all possible". Sometimes the answer to a question is "here's the way you should do it, but here is the less optimal way you might have to do it". There are very few "right" answers in programming, and more often than not the answer is "it depends".
That did not do it. This did not call the function and did not continue to execute the other statements after eval(stop_function).
@user823527 It definitely works, given what code you have posted so far: jsfiddle.net/7AfCc Your problem lies elsewhere... Check the JS condole for errors.
OK. It does work. I had to provide the object ID with that function call. Thanks.
1

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

Comments

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

3 Comments

It would make more sense to create the stopFunction() outside the clear_viewer. Looking at this "simple" sample, declaring and executing it as function in the same method shouldnt be needed.
I agree, but it's a literal answer to the OP's question not an architectural recommendation. That's not what he asked.
Agree, my comment was meant for the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.