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

π What Does this Mean in JavaScript?
Simple meaning:
π this means βwho is calling the function.β
It refers to the object that is executing the function.
π 1οΈβ£ this Inside Normal Functions
Example:
function show() {
console.log(this);
}
show();
In browser:
thisβ window object
In strict mode:
thisβ undefined
But donβt go deep right now.
Just remember:
π In a normal function, this depends on how the function is called.
π 2οΈβ£ this Inside Objects
This is where it becomes useful.
let person = {
name: "Rahul",
greet: function() {
console.log("Hi, I am " + this.name);
}
};
person.greet();
Output:
Hi, I am Rahul
Why?
Because:
π person is calling greet()
So this = person object
π What is call()?
call() lets you borrow a function and set this manually.
Example
let person1 = {
name: "Rahul"
};
let person2 = {
name: "Aman"
};
function greet() {
console.log("Hello " + this.name);
}
greet.call(person1); // Hello Rahul
greet.call(person2); // Hello Aman
π call() sets who this should be.
call() with Arguments
function introduce(city) {
console.log(this.name + " lives in " + city);
}
introduce.call(person1, "Bhopal");
Arguments are passed normally (comma separated).
π What is apply()?
Same as call()
But arguments are passed as an array.
Example
introduce.apply(person1, ["Delhi"]);
Only difference:
call()β arguments separatedapply()β arguments inside array
π What is bind()?
bind() does NOT call the function immediately.
It returns a new function with fixed this.
Example
let newFunction = introduce.bind(person2);
newFunction("Mumbai");
Output:
Aman lives in Mumbai
π bind() stores the connection for later use.
π Difference Between call, apply, bind
| Method | Calls Immediately? | Arguments Format | Returns New Function? |
|---|---|---|---|
| call() | β Yes | Normal arguments | β No |
| apply() | β Yes | Array | β No |
| bind() | β No | Normal arguments | β Yes |
π Diagram Idea β Function β Caller Relationship
Function greet()
β
Called By
β
person object
β
this = person
π Assignment Practice
1οΈβ£ Create Object with Method
let student = {
name: "Aman",
show: function() {
console.log("Student: " + this.name);
}
};
student.show();
2οΈβ£ Borrow Method Using call()
let student2 = { name: "Neha" };
student.show.call(student2);
3οΈβ£ Use apply()
function introduce(city) {
console.log(this.name + " lives in " + city);
}
introduce.apply(student2, ["Jaipur"]);
4οΈβ£ Use bind()
let boundFunc = introduce.bind(student);
boundFunc("Indore");
π Final Understanding
this= who is calling the functioncall()= call now, set thisapply()= same as call, but array argumentsbind()= create new function, call later
