Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call each function in the list

I've got an array of functions and looking for a concise way to call each one in order.

fns = [
    function a() { console.log('a') },
    function b() { console.log('b') },
    function c() { console.log('c') },
]

this works:

fns.map(function (f) { f() })

and so does this:

fns.map(function (f) { Function.call.call(f) })

however this raises a TypeError:

fns.map(Function.call.call)

Why doesn't the latter example work?

like image 822
georg Avatar asked Apr 10 '13 10:04

georg


1 Answers

for (var i = 0, len = fns.length; i < len; i++) {
    fns[i].call();
};

Here's the working fiddle.

Use Function.prototype.call and Function.prototype.apply as above to call a function. With call and apply you can pass execution scope and arguments to the function call. If you don't need that, you can simply do:

for (var i = 0, len = fns.length; i < len; i++) {
        fns[i]();
};

About your code:

Array.prototype.map is a function that takes callback and scope as parameters. In the first two examples, you are using an anonymous function as the callback and you call the parameter passed to it automatically by Array.prototype.map. To expand, your code is the equivalent of this:

function single(element) {
   element();
};
fns.map(single);

So the above is entirely correct. Following the same principle by using Function.call.call, you are calling the function f passed as a parameter by map.

But in your third example you are forcing a direct call via Function.call.prototype.call, however in this case, f no longer gets passed as a parameter, which means your Function.call.call will attempt to call undefined, hence you get the TypeError. When you put Function.call.call inside map(), you are NOT passing a callback as an argument.

The call will be immediately. Function.call.call is the exact same thing as Function.call.call(), or Function.call.call(undefined), which will be immediately evaluated when used as you did in your third example.

like image 77
flavian Avatar answered Sep 30 '22 03:09

flavian