The Problem: The Mystery of this
In JavaScript, the value of this depends on how a function is called.
Sometimes, you want to control what this refers to. This is where call,
apply, and bind come in. Think of them as tools to "steer" the this
keyword explicitly.

The Analogy: A Car (Function) and Its Driver (this)
Imagine functions as cars. Normally, the driver (this) is determined by who starts the car (calls the function). But what if you want to loan your car to a friend (a different object)? call, apply, and bind let you do this:
- call: "Drive my car now, and here’s a list of instructions (arguments)."
- apply: "Drive my car now, and here’s a box of instructions (array)."
- bind: "Here’s a clone of my car pre-configured for your use. Drive it whenever you want."
Interactive Examples
1. call(): Immediate Execution with Arguments
call() invokes a function immediately, specifying this and passing arguments
individually.
Without call, apply, or bind, the this context will be either:
undefined(in strict mode) or- The global object (in non-strict mode)
// Define objects and function
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };
function greet(greeting, punctuation) {
console.log("this value:", this);
console.log(`${greeting}, ${this.name}${punctuation}`);
}
// Call without setting 'this' context
console.log("Calling without call/apply/bind:");
greet("Hi", "!"); // Will throw error or show undefined for this.nameUsing call() to set 'this' context
// Define objects and a function
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
// Use call() to set 'this' to person1
greet.call(person1, "Hello", "!"); // Output: "Hello, Alice!"2. apply(): Immediate Execution with an Array
apply() works like call(), but accepts arguments as an .