What is the meanings of call.bind in Javascript?

Let get start with one common case, how we transform the array-like arguments object of a funciton to a real array?


// or more accurately

Common, indeed. Real meaning of this case: find the slice method on Array's prototype, and we can treat it is a static function, and bind arguments as this in it, and run.

Or imagine we put the first argument of call (arguments) in front of the method (slice) which is in front of call. Maybe you want to remember this kind of description or movement (put arguments in front of slice).

And recently, I discover something in this answer I cann't understand at my first sight, so I ask one new question about it.

var g = f.call.bind(f);

What that means?

So I ask one new question on stackoverflow. And soon I get two awesome answers. I will talk about the first in this article, and the second one next.

Still remember the [].slice.call(arguments)? What we want is the slice method and what we do is using call on it. It is same to f.call.bind(f), what we want here is the call method so f.call is as same as Function.prototype.call and what we do is using bind on it.

The difference between call and bind is just run a method or return a new funtion. And the movement, we can do it on f.call.bind(f), too. Replace what's in front of call by the first argument of bind, and we get f.call(just a frozen function, haven't run, waiting for its first argument) assigned to g.

What you can do with that?

Maybe you want to lowercasify an array of strings:

strings . map(''.toLowerCase.call)

Ha, you know it won't work! Because ''.toLowerCase.call just find the call method like a static function, it didn't know who want to make this call. Here it comes:

var call = Function.call
var toLowerCase = ''.toLowerCase

strings . map(call.bind(toLowerCase))

"Invoke call with the first argument passed in and ''.toLowerCase as this, which by virtue of the definition of call, means to call toLowerCase with that argument as this."

Or there is anther solution: strings . map(call, toLowerCase), but this is something else.


What call.bind(sth) do is make a function that sth is waiting to be called.