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

If you ask five different developers what this means, you might get five different answers. But the secret to understanding this is simple: It refers to the object that is currently executing the function. Think of it like the word "me" in English. When I say "me," I mean Abhinav. When you say "me," you mean you. The meaning changes depending on who is speaking.
The Golden Rule: Who is the Caller?
In JavaScript, this is determined by how a function is called, not where it is defined.
Inside a normal function: In a standalone function,
thisusually refers to the global object (the window in a browser).Inside an object method: When a function is part of an object,
thisrefers to the object itself.
// Example 1: Normal Function
function showThis() {
console.log(this);
}
showThis(); // Output: Window object
// Example 2: Object Method
const user = {
name: "InsideTech",
greet: function() {
console.log("Hi, I am " + this.name);
}
};
user.greet(); // Output: Hi, I am InsideTech (The 'user' called greet)
The Manual Overrides: Call, Apply, and Bind
Sometimes, you want to tell a function exactly what this should be, regardless of who called it. We use three power-tools for this: call(), apply(), and bind().
call() — Borrowing Methods
call() invokes a function immediately and lets you pass arguments one by one. It’s perfect for "borrowing" a method from one object to use on another.
const runner = { name: "Flash" };
user.greet.call(runner); // Output: Hi, I am Flash
apply() — The Array Specialist
apply() is exactly like call(), but instead of passing arguments one by one, you pass them as an array.
bind() — The Long-Term Commitment
Unlike the others, bind() does not run the function immediately. Instead, it creates a new copy of the function with thispermanently "locked" to a specific object. You can save this function and use it later.
const greetFlash = user.greet.bind(runner);
greetFlash(); // Output: Hi, I am Flash (even 10 minutes later!)
Conclusion
The this keyword is JavaScript's way of keeping code flexible. Instead of hardcoding names, we use this so our functions can work across different objects. Once you master call, apply, and bind, you have full control over the "context" of your code—giving you the power to borrow logic and reuse functions like a pro.



