📘 Classes & Inheritance in JavaScript
ES6 introduced the class
syntax in JavaScript, making it easier to create objects and implement inheritance using a cleaner, more familiar syntax (especially for developers coming from OOP languages like Java or C++).
🎓 Declaring a Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
const alice = new Person("Alice", 30);
alice.greet();
📚 Inheritance with extends
class Student extends Person {
constructor(name, age, subject) {
super(name, age); // Call parent constructor
this.subject = subject;
}
study() {
console.log(`${this.name} is studying ${this.subject}.`);
}
}
const bob = new Student("Bob", 22, "Mathematics");
bob.greet();
bob.study();
🔧 Method Overriding
Child classes can override parent methods:
class Teacher extends Person {
greet() {
console.log(`Hello students, I'm Professor ${this.name}.`);
}
}
const prof = new Teacher("Smith", 45);
prof.greet(); // Overridden version
🚀 Using super()
and super.method()
class Developer extends Person {
greet() {
super.greet(); // Call parent greet()
console.log("I write code every day!");
}
}
const dev = new Developer("Eve", 27);
dev.greet();
🧠 Summary
class
simplifies prototype-based inheritance.- Use
extends
to inherit from another class. super()
calls the parent constructor.- Child classes can override parent methods.
💡 Tip: Classes are syntactic sugar over JavaScript's prototypal inheritance. Behind the scenes, it's still using prototypes!