Assigning a call function to a variable and then calling it

I am struggling to figure out why the following is not working:

> var foo = Array.prototype.forEach.call;
< undefined

> typeof foo;
< "function"

> foo([1, 2, 3], function (y) {console.log(y);});
< Uncaught TypeError: foo is not a function
    at <anonymous>:2:1
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

      

While the alternative approach works very well:

var foo = Array.prototype.forEach;
foo.call([1, 2, 3], function (y) {console.log(y);});

      

I would be grateful for any hints.

+3


source to share


1 answer


fn.call

always takes context to go with it. You cannot just assign it to a variable, because then you are referencing Function.prototype.call

without including any context. Remember, Function.prototype.call()

it is not a decorator, but a property of a function that will help you deal with the correct execution of the context. When you break a link, you eliminate its purpose.



var foo = Array.prototype.forEach.call;
foo === Function.prototype.call //true
Array.prototype.forEach.call === Array.prototype.filter.call //true
Array.prototype.forEach.call === Object.prototype.hasOwnProperty.call //true

      

+2


source







All Articles