Mastering Call, Apply, and Bind in JavaScript: A Guide
In our previous blog post, we discussed the unique nature of ‘this’ in JavaScript and unveiled its magical power, as well as how it operates differently from other programming languages. If you’re interested in learning more about ‘this’ in the simplest way possible, check out our blog post: “Decoding ‘this’ Keyword”
During our exploration of ‘this,’ we discovered three built-in methods in JavaScript: .call(), .apply(), and .bind().
In JavaScript, .call(), .apply(), and .bind() are methods used to alter the reference of ‘this’ within a function and subsequently invoke it. This approach enables the explicit binding of ‘this’ for any given function.
Let’s begin -
Let’s check out the code -
const student1 = {
firstName: "Rishav",
lastName: "Pandey",
getName() {
console.log(`${this.firstName} ${this.lastName}`)
}
}
student1.getName() // Output: 'Rishav Pandey'
Here, we have a function called getName()
where this
points to its parent object, allowing us to retrieve the name. However, what if we have another student object with different values and we want to obtain the name?
We would end up creating another object, similar to this:
const student2 = {
firstName: "John",
lastName: "Doe",
getName() {
console.log(`${this.firstName} ${this.lastName}`)
}
}
student2.getName() // Output: 'John Doe'
We can see that we’ve ended up writing redundant code. So, what’s the solution?
Here comes our saviour — call(), apply(), and bind()
call() and apply()
call and apply are in-built methods that are automatically created whenever we create a regular function. We need to note that in the case of the arrow function, we don’t have this leverage.
Whenever we want to change the context of this, we can call/invoke that function with these two above methods and we’re done.
function getName() {
console.log(`${this.firstName} ${this.lastName}`)
}
const student1 = {
firstName: "Rishav",
lastName: "Pandey",
}
const student2 = {
firstName: "Ram",
lastName: "Krishna",
}
getName.call(student1) // Output: 'Rishav Pandey'
getName.call(student2) // Output: 'Ram Krishna'
Now without creating a getName()
multiple times we can access the properties of any object just by passing it as a reference of this
for a function every time it’s invoked.
Difference between call() and apply()
In terms of functionality and usage, both the call() and apply() behave in the same manner. It only differs on how the arguments are passed in terms of syntax if present.
call -
- Arguments are passed as a comma-separated value
apply-
- Arguments are passed as a single array with all arguments within it.
function getAnimal(food1, food2, food3) {
console.log(`${this.name} is ${this.mealPreference}, and likes to eat ${food1}, ${food2}, and ${food3}`)
}
const animal1 = {
name: "Lion",
mealPreference: "carnivorous"
}
const animal2 = {
name: "Deer",
mealPreference: "herbivorous"
}
getAnimal.call(animal1, "cheetahs", "crocodiles", "giraffes") // Output: 'Lion is carnivorous, and likes to eat cheetahs, crocodiles, and giraffes'
getAnimal.apply(animal2, ["Grasses", "sedges", "leaves"]) // Output: 'Deer is herbivorous, and likes to eat Grasses, sedges, and leaves'
bind() in Javascript
bind is also used to change the reference of this
inside any function, but it’s completely different in terms of functionality and usage when compared to call/apply.
bind is used to create a new function expression instead of invoking the function immediately which we usually see in call/apply.
function getName() {
console.log(`${this.firstName} ${this.lastName}`)
}
const student1 = {
firstName: "Rishav",
lastName: "Pandey",
}
const myName = getName.bind(student1)
myName()
In the code above, we can see that bind creates a new copy of the function to be invoked later, which is not the case with call/apply, where the function is immediately invoked.
Summary
In this article, we explored how to change the reference of ‘this’ using call, apply, and bind in JavaScript. Let’s briefly review each of them:
- call/apply — These two built-in methods are used to change the reference of ‘this’ within a function and invoke that function. The only difference between call and apply lies in how arguments are passed: call accepts parameters as comma-separated-values, while apply takes arguments in the form of an array.
- bind — This method differs when it comes to invoking a function. With bind, we obtain a new copy of the function that can be invoked later.
- All three methods are employed to change the reference of ‘this’ within the execution context of any function when it is invoked.
🌟 Enjoyed the read? I’d love to hear your thoughts! Share your takeaways and let’s start a conversation. Your insights make this journey richer for all of us.
👏 If you found this helpful, a clap or two would mean the world — it helps more folks find these guides!
🔜 What’s next? I’m already brewing the next topic, packed with more insights and a-ha moments. Stay tuned!
🙏 A big thank you for spending time with my words. Your support fuels my passion for sharing knowledge.
👋 Until next time, keep coding and keep exploring!
💬 Let’s stay connected! Follow me on Medium for more adventures in coding: https://thenomadtechie.medium.com/