Advanced · 12 min
Classes and encapsulation
Create instances that control their own state through methods.
Initialize an instance
A class groups construction and methods. new creates an instance and runs its constructor. Each instance can have its own values.
class Ticket {
constructor(price) { this.price = price; }
total(quantity) { return this.price * quantity; }
}
console.log(new Ticket(4).total(3));Output
12
Protect internal state
A private field beginning with # can be accessed only within the declaring class. Expose methods that keep updates valid.
class Counter {
#value = 0;
increment() { this.#value += 1; }
read() { return this.#value; }
}
const counter = new Counter();
counter.increment();
console.log(counter.read());Output
1
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Update private state
Make add increase the private quantity by the supplied amount. Display the quantity after adding 3.
Add amount instead of 1.