Method Chaining with this
You'll learn: How to build fluent interfaces where each method returns this to enable continuous chaining.
The Concept
When a method returns this, you can call another method on the result immediately. This creates a chain of method calls that reads smoothly, like sentences in natural language.
Think of it like a assembly line where each worker passes the same product to the next station. The product (your object) moves through multiple operations without stopping:
product.paint().polish().inspect().package()
Each step returns the product itself, ready for the next operation.
Why Return this?
Without returning this, you'd need to write repetitive code:
const builder = new QueryBuilder();
builder.select("name");
builder.where("age > 18");
builder.orderBy("name");
const query = builder.build();
With this as the return type, this becomes elegant:
const query = new QueryBuilder()
.select("name")
.where("age > 18")
.orderBy("name")
.build();
Basic Implementation
class QueryBuilder {
private fields: string[] = [];
private conditions: string[] = [];
select(field: string): this {
this.fields.push(field);
return this;
}
where(condition: string): this {
this.conditions.push(condition);
return this;
}
build(): string {
return `SELECT ${this.fields.join(", ")} WHERE ${this.conditions.join(" AND ")}`;
}
}
const query = new QueryBuilder()
.select("id")
.select("name")
.where("active = true")
.build();
Notice how select() and where() return this, not QueryBuilder. This subtle distinction becomes powerful with inheritance, which you'll encounter in later lessons.
Real-World Example: Form Builder
class FormBuilder {
private fields: Array<{ name: string; type: string }> = [];
private validations: Record<string, string[]> = {};
addField(name: string, type: string): this {
this.fields.push({ name, type });
return this;
}
require(fieldName: string): this {
if (!this.validations[fieldName]) {
this.validations[fieldName] = [];
}
this.validations[fieldName].push("required");
return this;
}
build() {
return {
fields: this.fields,
validations: this.validations
};
}
}
const loginForm = new FormBuilder()
.addField("email", "text")
.require("email")
.addField("password", "password")
.require("password")
.build();
Key Takeaway: Returning this from methods enables fluent, readable APIs where operations chain naturally. Use this as the return type annotation to maintain type safety across the chain.