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() |