Careeroza
Constructors and Methods
Methods and this
Example
Methods are functions on the class. Inside them, this refers to the object.
class Cart {
items: { name: string; price: number; qty: number }[] = [];
add(name: string, price: number, qty = 1): void {
this.items.push({ name, price, qty });
}
total(): number {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
count(): number {
return this.items.reduce((sum, i) => sum + i.qty, 0);
}
}
const cart = new Cart();
cart.add("Pen", 20, 5);
cart.add("Notebook", 60, 2);
console.log("Items:", cart.count(), "| Total: Rs.", cart.total());Output
Items: 7 | Total: Rs. 220
Parameter Properties (Shortcut)
Example
Adding public, private or readonly to a constructor parameter declares and assigns the property in one step. You will see this everywhere in Angular and NestJS.
class Customer {
constructor(
public readonly id: number,
public name: string,
private phone: string,
) {}
maskedPhone(): string {
return "******" + this.phone.slice(-4);
}
}
const c = new Customer(1, "Lakshmi", "9876543210");
console.log(c.id, c.name, c.maskedPhone());Output
1 Lakshmi ******3210
Losing this
Example
Passing a method as a callback loses this. An arrow-function property keeps it. (The full story of access modifiers is in the medium level.)
class Counter {
count = 0;
incrementMethod() { this.count++; }
incrementArrow = () => { this.count++; };
}
const c = new Counter();
const run = (fn: () => void) => fn();
run(c.incrementArrow);
console.log(c.count);
try {
run(c.incrementMethod);
} catch (e) {
console.log("Error:", (e as Error).message);
}Output
1 Error: Cannot read properties of undefined (reading 'count')