Module 28 : Call, Apply, and Bind Methods in javascript
1 : Introduction to this in JavaScript
🔍 What is this?
In JavaScript, this refers to the object that is executing the current function. However, the value of this changes depending on how the function is called.
javascript code
const person = { name: 'Rehana', greet: function() { console.log(`Hello, my name is ${this.name}`); } }; person.greet(); // Hello, my name is Rehana
But what happens when you detach the method?
javascript code
const greetFn = person.greet; greetFn(); // Hello, my name is undefined (or window/global)
This is where call, apply, and bind come in — to control or fix the this context.
2 : The call() Method
📘 Syntax:
javascript code
func.call(thisArg, arg1, arg2, ...)
📖 Description:
call() invokes a function immediately with a specified this context.
You pass arguments one-by-one after the context.
✅ Example:
javascript code
function introduce(language) { console.log(`${this.name} speaks ${language}`); } const user = { name: 'Ayesha' }; introduce.call(user, 'JavaScript'); // Output: Ayesha speaks JavaScript
🧠 Use Case:
Use call() when you need to borrow methods from other objects.
javascript code
const person1 = { name: 'John' }; const person2 = { name: 'Doe' }; function sayHi() { console.log(`Hi, I am ${this.name}`); } sayHi.call(person1); // Hi, I am John sayHi.call(person2); // Hi, I am Doe
3: The apply() Method
📘 Syntax:
javascript code
func.apply(thisArg, [argsArray])
📖 Description:
Similar to call(), but you pass arguments as an array.
✅ Example:
javascript code
function introduce(language, level) { console.log(`${this.name} speaks ${language} at ${level} level`); } const user = { name: 'Ali' }; introduce.apply(user, ['Python', 'Intermediate']); // Output: Ali speaks Python at Intermediate level
🔬 Use:
Perfect when arguments are already in array form:
javascript code
Math.max.apply(null, [5, 1, 7, 3]); // 7
4 : The bind() Method
📘 Syntax:
javascript code
const boundFunc = func.bind(thisArg, arg1, arg2, ...)
📖 Description:
bind() does not call the function immediately.
It returns a new function with the given this value permanently bound.
Useful in asynchronous code or event handlers.
✅ Example:
javascript code
const person = { name: 'Sara', greet: function() { console.log(`Hi, I'm ${this.name}`); } }; const greetSara = person.greet.bind(person); setTimeout(greetSara, 1000); // Hi, I'm Sara
Exercise Example:
javascript code
function multiply(x, y) { return x * y; } const double = multiply.bind(null, 2); console.log(double(5)); // 10
5 : Exercises
Exercise 1 : Use call to Borrow a Method
javascript code
const car = { brand: 'Toyota', show: function() { console.log(`Brand: ${this.brand}`); } }; const bike = { brand: 'Yamaha' }; // Use car's method for bike car.show.call(bike); // Brand: Yamaha
Exercise 2 : Use apply to Pass Arguments Dynamically
javascript code
function sum(a, b, c) { return a + b + c; } const numbers = [1, 2, 3]; console.log(sum.apply(null, numbers)); // 6
Exercise 3 : Use bind in Asynchronous Context
javascript code
const counter = { count: 0, increment: function() { this.count++; console.log(this.count); } }; const incrementLater = counter.increment.bind(counter); setTimeout(incrementLater, 1000); // 1
6 : Comparison Table
Feature
call()
apply()
bind()
Calls Function
Yes
Yes
No (returns function)
Argument Type
List of arguments
Array of arguments
List of arguments
Context Change
Yes
Yes
Yes (permanent)
Use Case
Borrow function
Spread arguments easily
Delay execution with context
7 : Research Insights
🔍 What Experts Say:
MDN: "call(), apply(), and bind() are essential to mastering dynamic function behavior and controlling execution context."
ECMAScript 5 introduced bind() due to growing needs for context preservation in callbacks and asynchronous programming.
📚 Deep Dive Sources:
MDN Web Docs – Function.prototype.call()
JavaScript.info – Call/Apply/Bind
Kyle Simpson, You Don’t Know JS (book series)
8 : Tips
💬 Analogy:
Think of call() and apply() as immediate function execution with context injection.
Think of bind() as creating a function with "memory" of its context.
🖼️ Visualization:
Draw 3 boxes on the whiteboard labeled as:
Function
this Object
Execution Result
Then connect how each method affects them.
9 : Mini Project
💡 Build a Logger Utility
Create a logger function that logs messages with different contexts.
javascript
code
function logMessage(prefix, message) { console.log(`${prefix}: ${message} - (${this.user})`); } const admin = { user: 'Admin123' }; const user = { user: 'User456' }; const adminLogger = logMessage.bind(admin, 'INFO'); adminLogger('System rebooted'); // INFO: System rebooted - (Admin123) logMessage.call(user, 'WARNING', 'Low battery'); // WARNING: Low battery - (User456)
✅ Summary
call(), apply(), and bind() give you control over the function's execution context.
Use them to fix broken contexts, reuse logic, and write cleaner asynchronous code.
Understanding them is vital for working with libraries like React, Vue, and even Node.js.
📘 for Learners
Recreate a simple version of .bind() manually.
javascript
code
Function.prototype.customBind = function(context, ...args) { const func = this; return function(...innerArgs) { return func.apply(context, [...args, ...innerArgs]); }; };
Test it and compare with the native bind() method.
No comments:
Post a Comment