1

I know that bind will bind methods this to the object being passed. But, what I am not understanding here is that, why are we passing the class name to the bind?

One answer I got from an expert was, "this is to make the function 'independent'" which again, I didn't understand. I might be completely stupid to not understand and go completely mad over one statement, but, could anybody please explain this?

Manu
  • 13
  • 4

1 Answers1

4

It's not a "class name," it's an object. (Specifically, a function; functions are objects in JavaScript. Even more specifically, a constructor function.)

Promise.all(...) looks up the all property on the Promise object and calls all with this set to Promise. So to do that with just all(...), we need to bind the function so that this is always Promise even when we call it a different way. That's what all = Promise.all.bind(Promise) does.

If we just did all = Promise.all, then when we called all(...), this during the call would not refer to Promise (it would be the global object in loose mode or undefined in strict mode). all relies on this referring to a constructor function for promises (Promise, for instance).

I know that bind will bind methods this to the object being passed

Let's put that a different way: a = b.bind(c) returns a new function (a) that, when called, will call b ensuring that this is set to c during the call. The result is called a bound function, because its this value is bound to it.

See also:

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • *(Gah! If that last paragraph seems to have `a` and `b` mixed up, hit refresh.)* – T.J. Crowder Aug 15 '17 at 13:38
  • Ok, I think i got it now! So... If we are "extracting" a function from its parent, we should make sure we bind its `this` to a proper object, so that we will not get any unexpected results. In this case, we are assigning `all` functions `this` to its actual parent, so that it will become autonomous. – Manu Aug 15 '17 at 13:59