Going Further Lesson 29 of 30
JavaScript Classes
Create many similar objects from one blueprint with class, constructor and methods, and extend a class with inheritance. Includes a bank-style savings account.
Suppose your app has 40 students, and each student object needs the same properties and the same methods. Instead of writing 40 objects by hand, you write one class: a blueprint for creating objects of the same kind.
A first class
<pre id="out"></pre>
<script>
class Student {
constructor(name, grade) {
this.name = name;
this.grade = grade;
this.scores = [];
}
addScore(score) {
this.scores.push(score);
}
average() {
if (this.scores.length === 0) return 0;
return this.scores.reduce((a, b) => a + b, 0) / this.scores.length;
}
}
const ana = new Student("Ana", 9);
ana.addScore(88);
ana.addScore(94);
const ben = new Student("Ben", 10);
ben.addScore(79);
document.getElementById("out").textContent =
`${ana.name} (Grade ${ana.grade}): ${ana.average()}\n` +
`${ben.name} (Grade ${ben.grade}): ${ben.average()}`;
</script>
class Student { ... }defines the blueprint. Class names start with a capital letter.constructorruns automatically when you create a new object. It sets up the properties.thismeans "the object being created or used".addScoreandaverageare methods, shared by every Student.new Student("Ana", 9)creates an object from the class. Each object is called an instance.
A savings account
<p>Balance: ₱<strong id="bal">0</strong></p>
<input id="amt" type="number" value="100" style="width:90px">
<button id="dep">Deposit</button>
<button id="wd">Withdraw</button>
<p id="msg"></p>
<script>
class BankAccount {
#balance = 0; // private: can't be changed from outside
constructor(owner) {
this.owner = owner;
}
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be more than ₱0.");
this.#balance += amount;
}
withdraw(amount) {
if (amount > this.#balance) throw new Error("Kulang ang balance.");
this.#balance -= amount;
}
get balance() {
return this.#balance;
}
}
const acct = new BankAccount("Juan");
const amt = () => Number(document.getElementById("amt").value);
function run(action) {
const msg = document.getElementById("msg");
try {
action();
msg.textContent = "✅ Done.";
} catch (e) {
msg.textContent = "❌ " + e.message;
}
document.getElementById("bal").textContent = acct.balance.toFixed(2);
}
document.getElementById("dep").onclick = () => run(() => acct.deposit(amt()));
document.getElementById("wd").onclick = () => run(() => acct.withdraw(amt()));
</script>
Two new ideas here:
- Private fields:
#balancecan only be used inside the class. Outside code can't doacct.#balance = 1000000. The only way to change it is throughdepositandwithdraw, which enforce the rules. This idea is called encapsulation. - Getters:
get balance()lets you readacct.balancelike a property, while the class controls what's returned.
Inheritance with extends
A class can be built on top of another. The new class gets everything from the parent and can add more:
<pre id="out"></pre>
<script>
class Student {
constructor(name) { this.name = name; }
introduce() { return `Hi, I'm ${this.name}.`; }
}
class Officer extends Student {
constructor(name, position) {
super(name); // run the parent's constructor first
this.position = position;
}
introduce() {
return super.introduce() + ` I'm the class ${this.position}.`;
}
}
const a = new Student("Ben");
const b = new Officer("Carla", "President");
document.getElementById("out").textContent = a.introduce() + "\n" + b.introduce();
</script>
super(...) calls the parent's constructor, and super.introduce() calls the parent's version of a method. An Officer is a Student, with extra features.
When should you use classes?
For small scripts, plain objects and functions are enough. Classes help when you have many objects of the same kind with shared behavior: players in a game, products in a store, accounts in a bank system. You'll meet the same ideas (classes, objects, inheritance) in Java, C++, C# and Python. This style is called object-oriented programming (OOP).
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04