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?
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() .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.