Call each function in the list

functional-programming, javascript

Solution

This simplified code exhibits a similar issue:

var x = Function.call.call;
x(alert);

In this case, once `Function.call.call` gets called, it won't remember the context from which it originated (i.e. `Function.call`). To save this context, you could use this unholy construct trick:

Function.call.bind(Function.call)

It returns a new function whereby the context of `Function.call` is bound to itself, thus saving the context. You can save this expression in a new variable:

var callFn = Function.call.bind(Function.call);

Now, `callFn(alert)` is identical to `alert.call()`. Note that any additional arguments will be passed along as is, so `callFn(alert, window)` will invoke `alert.call(window)`. Understanding this behaviour is important in situations when `callFn` gets called as part of a callback such as `Array.forEach`, whereby three arguments are passed in each iteration.

fns.forEach(callFn);

In your case, none of the functions inside `fns` are using the arguments that are passed, but behind the scenes they're called like this:

fns[0].call(0, fns)

So `this` equals the element's index (i.e. `Number(0)`) and `arguments[0]` equals the array of functions. The keen observer may have noticed that the element's value falls in between the cracks, though it may still be referenced using `arguments[0][this]` or, alternatively, `arguments.callee` (deprecated).

Problem

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?

Original source