最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I call a function defined in a javascript variable - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Feb 2, 2012 at 18:08 user823527user823527 3,71217 gold badges69 silver badges111 bronze badges 1
  • Why are you storing the function as string, simply call jwplayer().stop()? – proko Commented Feb 2, 2012 at 18:14
Add a ment  | 

3 Answers 3

Reset to default 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();
}

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();
function clear_viewer() {
     var stop_function = function(){ jwplayer.stop();};
     stop_function();
}
发布评论

评论列表(0)

  1. 暂无评论