Can someone explain logic behind
Function.prototype.call.bind(Array.prototype.forEach);
As I read 'bind' function give to function on which is called a context of object in which to executs.
But in this case bind receive function. So according to me this is not intuitive syntax. If i have further
myOtherFunction.call(this)
is call is still connected with context of forEach?
-
Perfect examples given here developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Scott Mitchell– Scott Mitchell2014年08月10日 14:46:10 +00:00Commented Aug 10, 2014 at 14:46
1 Answer 1
Array.prototype.forEach is a method, bound to the context of an array. So you could easily iterate over an array like:
[1,2,3].forEach(function(x){ console.log(x) })
This is equivalent to:
[].forEach.call([1,2,3],function(x){ console.log(x) })
So you are passing [1,2,3] as the current context (this) of your call into forEach().
What Function.prototype.call.bind(Array.prototype.forEach); does is calling (call) the bind function with another function (Array.prototype.forEach) as its current context to a variable.
var forEach=Function.prototype.call.bind(Array.prototype.forEach);
means literally spoken: »If a function call on forEach is made, please call it like you would, if you were in the context of Array.prototype.forEach.«
It is a shortcut to [].forEach.call(this,function)
For further references see MDN on Function.prototype.call(), Function.protoype.bind().