Reputation: 19453
Normally we can do this:
var somefunc = function(){
this.func1 = function(){ .... }
this.func2 = function(){ .... }
};
myvar = new somefunc();
Then we can call myvar.func1()
to run the function.
But, just my thinking. Is it possible to store functions into array and then we can just run all the functions in the array by loop through the array? If possible, then how can I push a function into array?
Thank you.
Upvotes: 1
Views: 965
Reputation: 141829
Yes, it is possible. Have you tried it? It works just like you would expect:
var funcs = [
function (){ console.log('foo'); },
function (){ console.log('bar'); },
];
for (var i = 0; i < funcs.length; i++) {
funcs[i]();
}
Upvotes: 3
Reputation: 1571
Yes you can :
var lx = [
function(x){ console.log(x) },
function(y){ console.log(y) }
];
for(var i=0; i<lx.length; i++)
lx[i](i);
Upvotes: 2
Reputation: 45135
Yes
var myArrayOFunctions = [
function() { .... },
function() { .... }
]
myArrayOFunctions[0](); // runs the first function
Example: http://jsfiddle.net/6VB6Y/
The nice part of using an array (versus using an object) is that you can loop through them in order with a simple for
loop, whereas using a for...in
on an object does not guarantee the order. Also, you can push
new functions into your array easily:
myArrayOFunctions.push(function() { .... });
So you can provide a simple way to add hooks in your code where somebody using your code can attach new functions to execute when some event happens.
Upvotes: 1
Reputation: 318192
Sure you can, something like this
var arr = [
function() {
console.log('fn 1')
},
function() {
console.log('fn 2')
},
function() {
console.log('fn 3')
}
]
arr.forEach(function(el) {
el();
});
Works perfectly fine, the same with objects or anywhere else you'd like to store a function, as functions are just objects
to push another function to the array, you'd do
arr.push(
function() {
console.log('fn 4')
}
);
easy as that
Upvotes: 8
Reputation: 1670
Functions in javascript are first class citizens, so the answer is yes.
From wikipedia: "In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures."
Upvotes: 3