The Magic of this, call(), apply(), and bind() in JavaScript

In JavaScript, functions are like versatile tools. Sometimes a tool needs to know who is using it to work correctly. This is where the keyword this and the methods call, apply, and bind come into play. They allow us to control the context of our code with precision.
What is this? (The "Who is Calling" Rule)
The simplest way to understand this is to ask: "Who is calling the function?" this is a keyword that refers to an object. Which object it refers to depends on how the function is being invoked.
In a normal function:
thisusually refers to the global window (in a browser).Inside an object method:
thisrefers to the object that "owns" the method.
JavaScript
const person = {
name: "Alice",
greet: function() {
console.log("Hi, I am " + this.name);
}
};
person.greet(); // Output: "Hi, I am Alice"
// Here, 'this' is 'person' because person is calling greet().
Borrowing Methods with call() and apply()
Sometimes you have a function in one object, but you want to use it for a different object. Instead of rewriting the code, you can "borrow" the method using call() or apply().
1. The call() Method
call() invokes the function immediately. The first argument is what you want this to be, followed by any individual arguments the function needs.
JavaScript
function introduce(city, country) {
console.log(`\({this.name} lives in \){city}, ${country}`);
}
const user1 = { name: "John" };
// We call the function and tell it 'this' should be user1
introduce.call(user1, "Paris", "France");
// Output: "John lives in Paris, France"
2. The apply() Method
apply() is exactly like call(), but with one key difference: it takes arguments as an array. This is helpful when you have a list of data and don't want to pass them one by one.
JavaScript
const user2 = { name: "Sara" };
const locationData = ["Tokyo", "Japan"];
introduce.apply(user2, locationData);
// Output: "Sara lives in Tokyo, Japan"
Saving Functions with bind()
Unlike call and apply, bind() does not run the function immediately. Instead, it creates a new version of the function with this "locked in" so you can use it later.
JavaScript
const user3 = { name: "Mike" };
// Create a new function that will ALWAYS use user3 as 'this'
const greetMike = introduce.bind(user3, "London", "UK");
// Later in your code...
greetMike(); // Output: "Mike lives in London, UK"
Quick Comparison Table
Feature | call() | apply() | bind() |
Execution | Immediate | Immediate | Returns a new function |
Arguments | Passed individually | Passed as an array | Passed individually |
Main Use | Method borrowing | Method borrowing with arrays | Setting context for later use (callbacks) |
Summary Checklist
thisis the object currently executing the code.Use
callwhen you want to execute a function immediately with a specificthis.Use
applywhen your arguments are already in an array.Use
bindwhen you want a function to remember itsthiscontext for future use.






