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 03 Answers
Reset to default 7You 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/