Careeroza
Private Fields
Encapsulation with #
Example
Fields and methods starting with # can only be used inside the class:
class Wallet {
#balance = 0;
#log(msg) { console.log("[wallet]", msg); }
add(amount) {
if (amount <= 0) throw new Error("Amount must be positive");
this.#balance += amount;
this.#log("added " + amount);
}
get balance() { return this.#balance; }
}
const w = new Wallet();
w.add(300);
console.log(w.balance);
console.log(Object.keys(w)); // private fields are invisibleOutput
[wallet] added 300 300 []
Exercise
Exercise: Create a class Rectangle with width and height, a getter area, and a static method square(size) that returns a square Rectangle.
Show answer
class Rectangle {
constructor(width, height) { this.width = width; this.height = height; }
get area() { return this.width * this.height; }
static square(size) { return new Rectangle(size, size); }
}
console.log(Rectangle.square(4).area); // 16