1

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?

1

1 Answer 1

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().

answered Aug 10, 2014 at 15:11
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.