Function.prototype: apply(), call(), bind()

Function.prototype.apply()

What does it need?

It takes it in context and optional arguments array.

How do we use it?

If I write func.apply(context, arguments), I like to think of the code actually executing as context.func(arguments), where each element of arguments would be translated by func as a regular list of arguments (like arg1, arg2, ..., argN instead of as an array).

Why do we want to use it?

  1. Set the context to something that doesn’t have that function built into it.
  2. Passing in an entire array of arguments to another function, like in a callback.

How do we remember it?

A for apply is A for array. apply() invokes the function now.

Function.prototype.call()

What does it need?

It takes in a context and, optionally, explicitly listed arguments (arg1, arg2, ..., argN). Note that this list of arguments is NOT an actual arguments array!

How do we use it?

If I write func.call(context, arg1, arg2, arg3), I imagine that the code is actually executed as context.func(arg1, arg2, arg3). This can be especially useful for copying only a select portion of the arguments array: Array.prototype.slice.call(arguments, 1)

I imagine this code executes as arguments.slice(1). This would not work had we used apply(). (Can you figure out why?)

Why do we want to use it?

  1. Like apply(), to explicitly set the context to whatever we want it to be.
  2. Again, like apply(), to pass in arguments to another function (like a callback), except now we have to state each argument as a list.

How do we remember it?

C for call is… not… A for array… so, pass arguments in one-at-a-time!
Also, calling something is invoking something, so are indeed invoking the function now instead of saving a copy for later!

Function.prototype.bind()

What does it need?

It takes in a context and, optionally, a list of arguments (just like Function.prototype.call()).

How do we use it?

bind() is used to set the context of a function (just like apply() and call()) EXCEPT it doesn't execute the function. Rather, it returns a copy of the function bound to a new context. This means the version returned from bind() must be executed at a later moment.

Why do we want to use it?

Like apply() and call(), to explicitly set the context to whatever want it to be WITHOUT immediately executing the function. A great use case is for setTimeout(). Typically, the first argument we pass into setTimeout() is a function we want to execute later, so we may want to throw in a "bind-ed" version of a function.

How do we remember it?

B for bind is not A for array… so, pass arguments in one-at-a-time!
bind() returns a copy of a function, so the original function is not invoked right now.