Methods Calling Other Methods
You'll learn how instance methods in a class can call other methods on the same object to organize complex behavior into smaller, reusable pieces.
The Core Idea
Just like functions can call other functions, methods inside a class can call other methods on the same instance using this. This lets you break down complicated tasks into simpler, focused methods that work together.
Think of it like a restaurant kitchen: the head chef doesn't do everything alone. They might call on the pastry chef for dessert and the sous chef for plating. Each person has their specialty, and they coordinate to create the final dish.
How It Works
Inside any instance method, you can call another method by using this.methodName(). Since this refers to the current instance, you're essentially telling the object to perform one of its own abilities.
class Calculator {
constructor(value) {
this.value = value;
}
add(num) {
this.value += num;
return this;
}
double() {
// Calling another method on the same instance
this.add(this.value);
return this;
}
addThenDouble(num) {
// Calling multiple methods in sequence
this.add(num);
this.double();
return this;
}
}
const calc = new Calculator(5);
calc.addThenDouble(3); // First adds 3 (= 8), then doubles (= 16)
console.log(calc.value); // 16
Why This Matters
Breaking behavior into smaller methods makes your code easier to understand, test, and maintain. Each method does one thing well, and complex operations become readable combinations of simple steps.
Key Takeaway: Methods can call other methods on the same instance using this.methodName(), enabling you to compose complex behaviors from simple, reusable building blocks.