This is part one of a three part series on JavaScript's bind()
, apply()
and call()
. These three methods are pretty closely related, but I think that each one deserves its own post! These concepts can be a little difficult to grasp, at least they were for me, so focusing on one at a time will be helpful!
The this
keyword:
- This tutorial covers just about everything you need to know about
this
.
First, let's take a look at the docs on bind()
from JavaScript MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
That explanation is a little rough, especially if you're new to JavaScript. Let's break it down!
-
bind()
returns a new function that has a specific value ofthis
bound to it when invoked. - The parameter passed into
bind()
will becomethis
. - You can add extra parameters to
bind()
after this initialthis
. - Use
bind()
when you want to call a function later on and with a specific context.
Here's an example without bind()
:
let meal = {
snack: "apple"
}
let eat = function(){
console.log(this.snack)
}
eat();
// will return undefined
Here is where bind()
comes in to save the day!
let boundEat = eat.bind(meal)
boundEat();
// returns "apple"
Now, let's see how we can add in those extra arguments!
let meal = {
type: "dinner",
consistsOf: "spaghetti and meatballs"
chef: function(name) {
return `Chef ${name} says: "We're having
${this.consistsOf} for ${this.meal}."`
}
}
let chefSays = meal.chef.bind(meal, "Remy")
// returns Chef Remy says: "We're having spaghetti and meatballs for dinner."
That's bind()
simplified!
Top comments (0)