Bind, Call, and Apply Readme
In this code along, we will be practicing the use of bind
, call
and apply
.
You can follow along using your browser's JS console, or use httpserver
to serve the provided index.html
. The HTML file will automatically load index.js
and edits you make there will be shown in your browser.
Objectives
Use
call()
andapply()
to invoke a function with an explicit value forthis
Explain the difference between
call()
andapply()
in the way you pass arguments to the target functionUse
bind()
to create new functions that are associated to specified contextsUse
bind()
to execute functions asynchronously
Alternate Ways to Invoke Functions
In our exploration of this
, we saw how it can change depending on how it is called. Let's take a look at a quick example. Copy and paste this into your browser's JS console to test for yourself:
However, when greet
is invoked as a method of an object, this
changes to refer to the object the method is invoked in. That is, the context automatically changes to be the containing object. Since person
has a name
property set, this.name
refers to the value 'bob'.
We've seen here that there are conditions where JavaScript will change the context ("what this
is set to) automatically. Developers can also force functions to be executed in other contexts. Javascript allows us to do this using the call
and apply
methods.
As you see above, we can use call
or apply
to invoke a function with a specified context. The context in which the function is to be run is passed in as the first argument to these methods.
NOTE: Our
greet
function is actually an instance of aFunction
class. Because of this a function instance can also have methods. Functions are things that run, but also things like{}
in JavaScript.
Both call
and apply
let us set the value of this
to whatever we pass as the first argument. The difference between the two is how arguments are passed to the function.
Passing Arguments With call
and apply
call
and apply
Let's modify our greet
function to be a little chattier:
Now, when we invoke greet
, not only do we need to explicitly set this
, but we also need to pass values for customerOne
and customerTwo
.
Using call
, we pass the object for this
as the first argument, followed by any function arguments in order.
Great! Now we see the name and the message! What happens if we don't pass any arguments?
The call to apply
works similarly to call
, except that apply
only takes two arguments: the value of this
, and then an Array
of arguments to pass to the function, like so:
You can remember the difference because apply
takes an array (both begin with the letter a). You can use either call
or apply
. The only difference is stylistic. Both exist because sometimes arguments need to be collected or bundled up (apply
) versus passed directly (call
).
Introduce bind
bind
So far, we have been looking at call
and apply
, which both explicitly set this
and then immediately execute the function call.
Sometimes, we want to take a function, associate it to a context and return a "context-bound" version of the original function.
Once we have the "context-bound" version of the function we can call it with (arguments, arguments, ...)
or call()
or apply()
without having to manually set the context. Let's see it in action.
As you see from the above code, by calling greet.bind(sally)
, we return a new function that we then assign to the variable newGreet
. Invoking newGreet
shows that the this
object is bound to sally
.
Note that the original greet
function is unchanged. bind
does not change it. Instead, bind
copies the function, and sets the copied function's this
context to whatever is passed through as an argument.
We can actually use bind and invoke immediately:
But this is just a noisy way of doing the same work of call()
or apply()
.
bind(), call(), and apply() in JavaScript code
Let's imagine we want to create an app that matches user interests with keywords from upcoming events. We could create a User
class and be able to assign properties to user instances, like a name and an array of interests. We can also include a class function, matchInterests
, that takes in an event and returns true if there are any matching keywords:
Here, a new User
instance is created and assigned to billy
. A name and interests are assigned as properties in the constructor
. We've also created a new Event
, with a title and keywords, assigned to freeMusic
.
matchInterests
is a class method that takes in an event object, checks to see if some event keywords are included in the user's interests, and returns true or false accordingly.
Except, when we call billy.matchInterests(freeMusic);
, that is not what happens. The problem in our code above is here:
Since every new function defines its own this
value, when the callback function is invoked, this
will be undefined
. We can see this by logging inside and outside the function:
In the first console.log
, this
refers to the billy
user instance. In the second, this
is undefined
. To solve this problem, we can use bind
:
Let's see why the above code works. When the matchInterests
method is invoked, this
refers to the User
instance context receiving the method call. We are in that context when our callback function is defined. Using bind
here lets us keep this
referring to the User
context.
A Brief Look at Arrow Functions
In modern JavaScript, arrow functions don't have their own this
, so this
will refer to whatever context the arrow function was invoked in. Using an arrow function, we could rewrite matchInterests
as:
Here, this
will refer to the User
instance context.
Summary
We reviewed how this
works for simple function calls. Then we saw how call
and apply
allow us to instantly execute functions while specifying the this
value of the executed function. Then we learned how to use bind
to make copies of functions with a new this
value bound to the copy of the function.
Resources
Last updated