Curriculum
Module 17 // Core JavaScript
Function Methods (call / apply / bind)
Module Objective
Explicit this binding patterns, method borrowing
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Method Borrowing
const runner = {
name: "Bolt",
logSpeed(speed) {
console.log(`${this.name} runs at ${speed}km/h`);
}
};
const car = { name: "Tesla" };
// Borrow logSpeed for the car
runner.logSpeed.call(car, 120); // "Tesla runs at 120km/h"💡 `.call()` allows an object to use a method belonging to another object without rewriting the code.
// Example 2
// 2. Using apply for Arrays
const nums = [5, 6, 2, 3, 7];
// Math.max expects separate arguments, not an array
const max = Math.max.apply(null, nums);
console.log(max); // 7
// Modern equivalent: Math.max(...nums)💡 `.apply()` is similar to `.call()`, but it takes arguments as an array. It was very useful before the Spread operator (`...`) existed.
// Example 3
// 3. Permanently binding context
const counter = {
count: 0,
inc() {
this.count++;
console.log(this.count);
}
};
const buttonInc = counter.inc.bind(counter);
// Even when called loosely, 'this' stays fixed
setTimeout(buttonInc, 1000); // 1💡 `.bind()` returns a **new function** with the context permanently set. It's the standard way to fix the 'lost context' bug in callbacks.
Engine & Memory Architecture
Behind the Scenes
1. Function Prototype:
- These methods live on
Function.prototypein the Heap. - Every function has access to them via the Prototype Chain.
2. New Object Allocation:
- .bind(): Creates a new function object in the Heap. This new object wraps the original function and holds a hidden reference to the bound context.
- .call() / .apply(): Do not create new functions; they immediately invoke the original function with a modified Stack Frame.
3. Performance:
- .call()/.apply() are very efficient.
- .bind() should be used carefully in loops or frequently rendered components (like React) because each call allocates new memory in the RAM.