3

I'm struggling to figure out why following doesn't work:

> 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 alternative approach works just fine:

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

I would be grateful for any hints.

TaoPR
  • 5,932
  • 3
  • 25
  • 35
Adrian Baran
  • 885
  • 7
  • 23

1 Answers1

2

fn.call always takes a context to go with it. You can't just assign it to a variable because then you're referencing the Function.prototype.call without including any context. Remember, Function.prototype.call() is not a decorator but a property of a function to help you with deal with correct context execution. When you break the reference, you have eliminated 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
Bwaxxlo
  • 1,860
  • 13
  • 18