JavaScript Power Trio: Mastering Call, Apply, and Bind
If you have been working with JavaScript for a while, you’ve likely bumped into the this keyword. It’s powerful, but it can be slippery. Sometimes this doesn’t refer to what you think it does. This is…
Swarup Das
On this page
If you have been working with JavaScript for a while, you’ve likely bumped into the this keyword. It’s powerful, but it can be slippery. Sometimes this doesn’t refer to what you think it does.
This is where Call, Apply, and Bind come to the rescue. These three methods allow you to explicitly determine what this refers to, giving you full control over the execution context of your functions.
Let's break them down.
The Setup: A Real-World Example
Imagine we have a person object with a first and last name. We also have a standalone function greet that is not attached to the object but uses this to access data.
const person1 = {
firstName: "John",
lastName: "Doe"
};
const person2 = {
firstName: "Sarah",
lastName: "Smith"
};
function greet(greeting, punctuation) {
console.
Leave a Comment