A class is a blueprint for creating many similar objects.
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
result() {
return this.marks >= 33 ? 'Pass' : 'Fail';
}
}
const s1 = new Student('Asha', 82);
s1.result(); // 'Pass'
Key words
constructorruns when you create an object withnew- Methods are written without the
functionkeyword thisrefers to the current object
Inheritance
class Topper extends Student {
constructor(name, marks, rank) {
super(name, marks); // call the parent constructor
this.rank = rank;
}
}
Example
Example — Bank account class
HTML
<pre id="out"></pre>
<script>
class Account {
constructor(owner, balance = 0) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) { this.balance += amount; return this; }
withdraw(amount) {
if (amount > this.balance) throw new Error('Insufficient balance');
this.balance -= amount;
return this;
}
toString() { return `${this.owner}: ₹${this.balance}`; }
}
class Savings extends Account {
constructor(owner, balance, rate) {
super(owner, balance);
this.rate = rate;
}
addInterest() { return this.deposit(this.balance * this.rate / 100); }
}
const acc = new Savings('Ravi', 1000, 5);
acc.deposit(500).addInterest();
let text = acc.toString();
try { acc.withdraw(99999); } catch (e) { text += '\n' + e.message; }
document.getElementById('out').textContent = text;
</script>