Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call all Javascript functions in a list

Tags:

javascript

What is the most idiomatic way to call all functions in a list?

The best I can think of is:

myFunctions.forEach(function(f){f();});

Is there a more idiomatic way of doing this?

EDIT:

I'm really only interested in ES5 for now. Perhaps there is some way having to do with Array prototypes?

like image 402
eatonphil Avatar asked May 21 '15 19:05

eatonphil


Video Answer


2 Answers

What about ES6? You can use arrow function.

This would be :

myFunctions.forEach( f => f());

You can already use it today with tool like babel. For an overview of ES6 features check out es6features.

EDIT:

You can extend the Array object with the following method:

Array.prototype.invokeFunctions = function () {
    this.forEach(function (f) {
    if (typeof(f) === "function")
      f()
    });
}

var functions = [
    function () { console.log(1);},
    function () { console.log(2);}
];

functions.invokeFunctions();
// output 
1
2

However, I don't think this is a good idea as it pollutes the global Array prototype. A better idea could be to use an object designed explicitly for this purpose. For example:

function FunctionList(functions) {
  this.functions = functions;
}

FunctionList.prototype.callAll = function () {
  this.functions.forEach(function (f) {
    if (typeof(f) === "function")
      f()
  });
}

var functionList = new FunctionList(functions);
functionList.callAll();

This is a better solution in my opinion. Every time you have a function array you can wrap it in a FunctionList object. However in this case you lose all the benefits of using an Array and you have to implement getter and setter methods if you want to modify/access the function array.

like image 149
Giuseppe Pes Avatar answered Oct 10 '22 06:10

Giuseppe Pes


You could get tricky and use prototype methods, though it's not much more succinct:

myFunctions.map(Function.prototype.call, Function.prototype.call);

a wee bit shorter if you grab a reference to call:

var call = Function.prototype.call;
myFunctions.map(call, call);

or we could go nuts with prototype methods:

[].map.apply(fns, [call, call]);
like image 27
Rob M. Avatar answered Oct 10 '22 04:10

Rob M.