admin管理员组文章数量:1355529
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/
本文标签: cArray of Function Pointers in JavaScriptStack Overflow
版权声明:本文标题:c++ - Array of Function Pointers in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743995796a2572965.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论