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

c++ - Array of Function Pointers in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

How can one implement an array of function pointers in JavaScript within their XHTML document? Today we learned in lecture how to implement JavaScript functions in an XHTML document, but what about arrays of function pointers? Can I pop a bunch of functions in an array and dereference them by index as one does in C++? Just curious...

How can one implement an array of function pointers in JavaScript within their XHTML document? Today we learned in lecture how to implement JavaScript functions in an XHTML document, but what about arrays of function pointers? Can I pop a bunch of functions in an array and dereference them by index as one does in C++? Just curious...

Share Improve this question asked Jan 29, 2014 at 22:41 user3250884user3250884 0
Add a ment  | 

3 Answers 3

Reset to default 7

You can just place references to your functions in an array. For example:

function func1() { alert("foo"); }
function func2() { alert("bar"); }
function func3() { alert("baz"); }
var funcs = [ func1, func2, func3 ];

funcs[0](); // "foo"

Of course, you can just as easily use anonymous functions like this:

var funcs = [ 
    function() { alert("foo"); }, 
    function() { alert("bar"); }, 
    function() { alert("baz"); } ];

funcs[0](); // "foo"

There are no such things as pointers in JavaScript. Therefore there's no need "dereference". You can use functions and put them in arrays however you like:

var fns = [ f1, f2, function() { console.log('!'); } ];

You can access and call them by doing:

fns[2]();

If your code is looking through that array and executing those functions, you should also make sure they actually are valid functions. You can do it in pure javascript, but jQuery and other libraries have handy "isFunction" checkers that I would use for simplicity and clarity.

http://api.jquery./jquery.isfunction/

发布评论

评论列表(0)

  1. 暂无评论