Imagine you have a robot named Bob 🤖. Bob can introduce himself and say where he is from. But sometimes, you want Bob to introduce someone else!
This is where call()
, apply()
, and bind()
help! They let you borrow a function from one object and use it for another object.
Table of Contents
1️⃣ call()
– Call Me Now! 📞
Think of call()
like borrowing a friend’s phone and making a call immediately.
📌 Example
Bob the robot has a function to introduce himself:
const bob = { name: "Bob", greet: function (city) { console.log(`Hello, I am ${this.name} from ${city}!`); } };
Now, Alice wants to introduce herself using Bob’s function:
const alice = { name: "Alice" }; bob.greet.call(alice, "New York"); // Output: "Hello, I am Alice from New York!"</code>
🏆 Key Takeaways
call()
immediately runs the function.- The first argument is the object (
this
). - The next arguments are passed individually.
2️⃣ apply()
– Call Me with a List! 📜
Think of apply()
like sending a text message but using a list of words instead of typing them separately.
📌 Example
Bob’s function again:
bob.greet.apply(alice, ["Paris"]); // Output: "Hello, I am Alice from Paris!" </code>
🏆 Key Takeaways
apply()
works just likecall()
.- The difference? Arguments are passed as an array.
3️⃣ bind()
– Save My Number for Later! ⏳
Think of bind()
like saving a friend’s number in your phone. You don’t call now, but you can call later.
📌 Example
const greetAlice = bob.greet.bind(alice, "London"); greetAlice(); // Output: "Hello, I am Alice from London!" </code>
🏆 Key Takeaways
bind()
does not call the function immediately.- It returns a new function that you can call later.
- You can preset some arguments (like
"London"
in this case).
🎯 Final Comparison Chart
Method | When does it run? | How are arguments passed? | Returns a new function? |
---|---|---|---|
call() | Immediately | Individually: func.call(thisArg, arg1, arg2, …) | ❌ No |
apply() | Immediately | As an array: func.apply(thisArg, [arg1, arg2, …]) | ❌ No |
bind() | Later (when you call it) | Individually (like call() ) | ✅ Yes |
🎭 Fun Real-World Example
Imagine you are a teacher 👩🏫 and you have a function to grade students.
const teacher = { subject: "Math", grade: function (student, marks) { console.log(`${student} got ${marks} in ${this.subject}.`); } }; const scienceTeacher = { subject: "Science" }; // ✅ `call()`: Call now! teacher.grade.call(scienceTeacher, "John", 85); // Output: "John got 85 in Science." // ✅ `apply()`: Call now with array! teacher.grade.apply(scienceTeacher, ["Emily", 90]); // Output: "Emily got 90 in Science." // ✅ `bind()`: Save for later! const gradeJohn = teacher.grade.bind(scienceTeacher, "John", 88); gradeJohn(); // Output: "John got 88 in Science." </code>
🏆 When to Use What?
Scenario | Use |
---|---|
Need to call a function immediately? | ✅ call() |
Need to call a function immediately but with an array of arguments? | ✅ apply() |
Need to store a function for later? | ✅ bind() |