6

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...

0

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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

6 Comments

What does "console.log('!');" do?
@user3250884 it prints ! in your browser's JavaScript console. (usually you can access this by pressing F12)
@user3250884 It prints to the console the string "!".
Do you mean ! or "!"?
@user3250884 No, what you will see is !.
|
0

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.com/jquery.isfunction/

Comments

Your Answer

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