ES6 Classes and Inheritance in JavaScript
Quick Answer: ES6 classes provide a clear way to create objects in JavaScript. A class defines shared data and methods. Inheritance lets one class reuse and extend another class. We use extends, super(), and method overriding to build related objects.
1. Why Do We Need Classes in JavaScript?
Imagine you manage a school with 1,000 staff members. Each staff member has a name, employee ID, and department. Teachers and principals also have different duties.
How would you store these details without repeating the same code? Think about adding another staff role next month.
The problem: Creating staff records without classes
We can create separate objects for every staff member. Each object stores its own details and duty function.
Example 1: Three school staff records without classes
const teacher = {
name: "Priya",
employeeId: "T101",
department: "Mathematics",
showDetails() {
console.log("Teacher: " + this.name);
}
};
const principal = {
name: "Ravi",
employeeId: "P101",
department: "Administration",
showDetails() {
console.log("Principal: " + this.name);
}
};
const librarian = {
name: "Lakshmi",
employeeId: "L101",
department: "Library",
showDetails() {
console.log("Librarian: " + this.name);
}
};
teacher.showDetails();
principal.showDetails();
librarian.showDetails();
Expected output
Teacher: Priya Principal: Ravi Librarian: Lakshmi
This works, but it gets hard to manage.
What goes wrong as the school grows?
- We repeat the same properties in every staff object.
- We repeat similar methods for each staff role.
- Changing shared details means editing many objects.
- Adding new staff roles creates more repeated code.
- Keeping all staff records consistent becomes harder.
Now think about 1,000 staff members across several departments. We need a better structure.
2. What Is an ES6 Class?
Class = a blueprint for creating objects.
Object = one actual staff member created from that blueprint.
ES6 classes were introduced in ECMAScript 2015, also called ES6. They provide cleaner syntax for JavaScript's existing prototype-based object system.
We can define shared properties and methods once. Then we create many objects from the same class.
Solution: Create a SchoolStaff class
We will use one class for the shared staff details. Each staff object will receive its own values.
Example 2: Create a class and three staff objects
class SchoolStaff {
constructor(name, employeeId, department) {
this.name = name;
this.employeeId = employeeId;
this.department = department;
}
showDetails() {
console.log(
`${this.name} - ${this.employeeId} - ${this.department}`
);
}
}
const teacher = new SchoolStaff(
"Priya", "T101", "Mathematics"
);
const principal = new SchoolStaff(
"Ravi", "P101", "Administration"
);
const librarian = new SchoolStaff(
"Lakshmi", "L101", "Library"
);
teacher.showDetails();
principal.showDetails();
librarian.showDetails();
Expected output
Priya - T101 - Mathematics Ravi - P101 - Administration Lakshmi - L101 - Library
Without classes vs with classes
| Without classes | With classes |
|---|---|
| Every staff object repeats its properties. | Shared properties are defined once. |
| Similar methods appear in many objects. | Methods are shared through the class prototype. |
| Changes need edits in several places. | Shared logic changes in one place. |
| New staff roles need more repeated code. | New objects can use the same class. |
| Shared structure is harder to maintain. | The structure is easier to understand. |
The idea to remember
- Class = blueprint for school staff records.
- Object = one staff member created from the class.
- Constructor = special method that sets initial values.
- Property = information stored on an object.
- Method = function defined inside a class.
- Instance = an object created from a class.
3. How Do JavaScript Classes Work?
3.1 The class keyword
The class keyword defines a new class. Its body contains a constructor and methods.
Class names usually start with a capital letter. This makes them easier to identify.
3.2 The constructor method
Constructor = the method that prepares a new object.
JavaScript calls the constructor when we use new. We normally use it to set the object's initial properties.
Example 3: Set initial staff details
class SchoolStaff {
constructor(name, employeeId) {
this.name = name;
this.employeeId = employeeId;
}
}
const staff = new SchoolStaff("Priya", "T101");
console.log(staff.name);
console.log(staff.employeeId);
Expected output
Priya T101
3.3 Understanding the this keyword
this refers to the current object in these instance methods.
For example, this.name stores the name on the current staff object. Each object keeps its own property values.
3.4 Creating objects with new
The new keyword creates an object from a class. It also runs the constructor automatically.
Each call to new SchoolStaff() creates a separate object. Changing one object's name does not change another object's name.
3.5 How a class becomes an object
The animation highlights the class first, then each staff object created from it.
4. What Is Inheritance in JavaScript?
Imagine the school adds more staff roles. Teachers and principals share some details. However, their daily duties are different.
We could create separate classes for each role. But shared properties would still appear repeatedly.
Inheritance = a way for one class to reuse another class's features.
The existing class is called the parent or base class. The new class is called the child or derived class.
4.1 The problem without inheritance
Look at these two classes. Both repeat the same staff details and constructor logic.
Example 4: Repeated properties in separate classes
class Teacher {
constructor(name, employeeId, department) {
this.name = name;
this.employeeId = employeeId;
this.department = department;
}
teach() {
console.log(`${this.name} teaches students.`);
}
}
class Principal {
constructor(name, employeeId, department) {
this.name = name;
this.employeeId = employeeId;
this.department = department;
}
manageSchool() {
console.log(`${this.name} manages the school.`);
}
}
const teacher = new Teacher(
"Priya", "T101", "Mathematics"
);
const principal = new Principal(
"Ravi", "P101", "Administration"
);
console.log(teacher.name);
console.log(principal.name);
Expected output
Priya Ravi
The code runs correctly. However, shared details are repeated in both classes.
4.2 Use extends to create a child class
The extends keyword connects a child class to a parent class. The child receives access to inherited methods.
We can keep common staff details inside SchoolStaff. Then we can create specific classes for teachers and principals.
Example 5: Create child classes using extends
class SchoolStaff {
constructor(name, employeeId, department) {
this.name = name;
this.employeeId = employeeId;
this.department = department;
}
showDetails() {
console.log(
`${this.name} - ${this.employeeId} - ${this.department}`
);
}
}
class Teacher extends SchoolStaff {
teach() {
console.log(`${this.name} teaches students.`);
}
}
class Principal extends SchoolStaff {
manageSchool() {
console.log(`${this.name} manages the school.`);
}
}
const teacher = new Teacher(
"Priya", "T101", "Mathematics"
);
const principal = new Principal(
"Ravi", "P101", "Administration"
);
teacher.showDetails();
teacher.teach();
principal.showDetails();
principal.manageSchool();
Expected output
Priya - T101 - Mathematics Priya teaches students. Ravi - P101 - Administration Ravi manages the school.
Both child classes reuse the parent constructor and method. Each child also defines its own role-specific method.
4.3 Visualise the inheritance relationship
The parent class is highlighted first. The inheritance links then lead to each child class.
5. Understand super() in JavaScript
super = a way for a child class to use its parent class.
We commonly use super() inside a child constructor. It calls the parent constructor with the supplied values.
When a child class defines its own constructor, it must call super() before using this.
5.1 Pass values to the parent constructor
The teacher needs common staff details and an additional subject. The parent stores the shared details. The child stores the subject.
Example 6: Use super() inside a child constructor
class SchoolStaff {
constructor(name, employeeId) {
this.name = name;
this.employeeId = employeeId;
}
}
class Teacher extends SchoolStaff {
constructor(name, employeeId, subject) {
super(name, employeeId);
this.subject = subject;
}
showTeacherDetails() {
console.log(
`${this.name} teaches ${this.subject}.`
);
}
}
const teacher = new Teacher(
"Priya", "T101", "Mathematics"
);
teacher.showTeacherDetails();
console.log(teacher.employeeId);
Expected output
Priya teaches Mathematics. T101
5.2 What happens when super() runs?
- JavaScript starts creating the new Teacher object.
- The child constructor receives the supplied values.
super(name, employeeId)calls the parent constructor.- The parent constructor assigns the shared properties.
- The child constructor assigns the subject property.
- The new Teacher object is ready for use.
Important: A derived class constructor cannot use this before calling super(). JavaScript throws a ReferenceError when you break this rule.
5.3 Use super to call a parent method
We can also use super.methodName() inside a child method. This calls the matching method from the parent class.
Example 7: Call the parent method from a child class
class SchoolStaff {
showDetails() {
console.log("School staff details");
}
}
class Teacher extends SchoolStaff {
showDetails() {
super.showDetails();
console.log("Teacher details");
}
}
const teacher = new Teacher();
teacher.showDetails();
Expected output
School staff details Teacher details
6. What Is Method Overriding?
Imagine the school wants every staff role to show its own duty. Teachers teach students. Principals manage school activities. Both roles need a method named showDuty().
Method overriding = a child class provides its own version of an inherited method.
The child method uses the same method name. JavaScript runs the child version when we call it on that child object.
6.1 Override a parent method
We will define a general duty in the parent class. Each child class will provide its own duty.
Example 8: Override showDuty() in child classes
class SchoolStaff {
constructor(name) {
this.name = name;
}
showDuty() {
console.log(`${this.name} works at the school.`);
}
}
class Teacher extends SchoolStaff {
showDuty() {
console.log(`${this.name} teaches students.`);
}
}
class Principal extends SchoolStaff {
showDuty() {
console.log(`${this.name} manages school activities.`);
}
}
const teacher = new Teacher("Priya");
const principal = new Principal("Ravi");
teacher.showDuty();
principal.showDuty();
Expected output
Priya teaches students. Ravi manages school activities.
6.2 How method overriding works
The animation follows the method call into each child class and highlights its own implementation.
6.3 Parent method vs overridden method
| Situation | Method that runs |
|---|---|
| Child does not define the method. | The inherited parent method runs. |
| Child defines the same method name. | The child method runs. |
Child calls super.showDuty(). |
The parent method runs from the child method. |
7. The Prototype Chain Behind Classes
JavaScript classes use prototypes behind the scenes. A prototype is an object that supplies shared properties and methods.
When we call a method, JavaScript first checks the object. If the method is missing, JavaScript checks its prototype. This search continues through the prototype chain.
For an inherited object, the child class prototype links to the parent class prototype. This is how inherited methods can be found.
Example 9: Check the prototype relationship
class SchoolStaff {
showDetails() {
console.log("Common staff details");
}
}
class Teacher extends SchoolStaff {
teach() {
console.log("Teaching students");
}
}
const teacher = new Teacher();
console.log(teacher instanceof Teacher);
console.log(teacher instanceof SchoolStaff);
console.log(
Object.getPrototypeOf(Teacher.prototype) === SchoolStaff.prototype
);
Expected output
true true true
The instanceof operator checks the prototype chain. It tells us whether an object belongs to a class or its derived class.
8. Important Class Features to Know
8.1 Class methods are shared through the prototype
Normal class methods are not copied into every object. They are stored on the class prototype and shared by instances.
This helps avoid creating a separate method function for every staff object.
8.2 Static methods
A static method belongs to the class itself. We call it using the class name, not an instance.
Example 10: Create a static staff helper
class SchoolStaff {
static getSchoolName() {
return "Green Valley School";
}
}
console.log(SchoolStaff.getSchoolName());
Expected output
Green Valley School
Calling getSchoolName() on a staff instance will not work. The method belongs to the class.
8.3 Getters and setters
A getter reads a value through property-like syntax. A setter controls how a value is assigned.
Example 11: Use a getter and setter for staff name
class SchoolStaff {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(value) {
this._name = value.trim();
}
}
const staff = new SchoolStaff("Priya");
staff.name = " Lakshmi ";
console.log(staff.name);
Expected output
Lakshmi
The underscore is a naming convention here. It does not make the property private.
9. Common Mistakes and Best Practices
Mistake 1: Forgetting super() in a child constructor
Wrong approach: Using this before calling super().
Incorrect code
class Teacher extends SchoolStaff {
constructor(name) {
this.name = name;
super(name);
}
}
Why it fails: A derived constructor must call super() before accessing this.
Correct approach: Call the parent constructor first.
Corrected code
class Teacher extends SchoolStaff {
constructor(name) {
super(name);
}
}
Rule: Call super() before using this in a derived constructor.
Mistake 2: Forgetting the extends keyword
Wrong approach: Creating a child class without extending the parent.
The child will not inherit the parent's methods. Use extends to establish the relationship.
Mistake 3: Calling a static method on an object
Wrong approach: Calling staff.getSchoolName() when the method is static.
Correct approach: Call SchoolStaff.getSchoolName() on the class.
Mistake 4: Repeating parent logic inside every child
Do not copy shared properties into every child constructor. Put shared setup in the parent constructor. Call it using super().
Mistake 5: Using inheritance for unrelated objects
Inheritance should represent a real "is a" relationship. A teacher is a type of school staff member. A school timetable is not a type of school staff member.
Best practice: Keep parent classes focused on shared behavior. Keep role-specific behavior inside child classes. Prefer composition when objects do not have a clear parent-child relationship.
10. Class Inheritance and Composition
Inheritance is useful, but it is not the answer to every reuse problem. Composition means building an object using other objects or services.
For example, a school staff member may use a notification service. That service does not need to be a parent class.
| Inheritance | Composition |
|---|---|
| Models an "is a" relationship. | Models a "uses a" relationship. |
| Shares behavior through a parent class. | Uses separate objects for behavior. |
| Creates a parent-child class structure. | Combines smaller independent parts. |
| Can become difficult with deep class trees. | Can make behavior easier to replace. |
| Useful for clear, stable type relationships. | Useful for flexible service behavior. |
11. How This Comes Up in JavaScript Interviews
Question 1: What are classes in JavaScript?
What the interviewer wants: They want to know if you understand class syntax and objects.
Strong answer: "A class is a template for creating objects. It defines properties and methods. We create an object using the new keyword. JavaScript classes use prototypes internally."
Question 2: What is inheritance in JavaScript?
What the interviewer wants: They want to hear how code reuse works between related classes.
Strong answer: "Inheritance lets a child class reuse a parent class's methods and properties. We use the extends keyword. The child can also add its own properties and methods. In our school example, Teacher extends SchoolStaff."
Question 3: What is the purpose of super()?
Strong answer: "We use super() to call the parent constructor. It helps initialize shared staff properties. A child constructor must call it before using this."
Question 4: What is method overriding?
Strong answer: "Method overriding happens when a child class defines a method with the same name as its parent. The child version runs for that child object. For example, Teacher and Principal can define different showDuty() methods."
Question 5: Are JavaScript classes based on prototypes?
Strong answer: "Yes. JavaScript classes use the prototype system internally. Instance methods are stored on the class prototype. Inheritance connects the child prototype to the parent prototype."
Question 6: Can JavaScript classes extend more than one class?
Strong answer: "No. A JavaScript class can extend only one class directly. We can use composition or mixins for other shared behavior."
Junior, senior, and architect expectations
- Junior developer: Explain classes, objects, constructors, and
extends. - Senior developer: Explain
super(), overriding, prototypes, and maintainability. - Technical architect: Explain inheritance trade-offs, composition, and class design boundaries.
12. Hands-On Practice
Beginner: Create a Student class
Create a Student class with a name, roll number, and class name. Add a method that prints the student's details.
Expected result: Create two students and print both records.
Intermediate: Create a Teacher child class
Create a SchoolStaff parent class. Add name and employeeId. Create a Teacher child class using extends.
Add a subject property to the teacher. Use super() to initialize the shared properties.
Expected result: Print the teacher's name, employee ID, and subject.
Advanced: Override a common method
Create Teacher and Principal child classes. Both should extend SchoolStaff.
Add a method named showDuty() to the parent. Override it in both child classes.
Expected result: Calling showDuty() should print each role's own duty.
Challenge: Check the prototype chain
Create a Teacher object. Check whether it is an instance of both Teacher and SchoolStaff.
Hint: Use the instanceof operator.
13. Key Takeaways
- ES6 classes provide cleaner syntax for creating JavaScript objects.
- The constructor sets the initial values of an object.
- The
newkeyword creates a class instance. - The
thiskeyword refers to the current object. - The
extendskeyword creates a child class. - The
super()call runs the parent constructor. - Use
super.methodName()to call a parent method. - Method overriding lets child classes provide their own behavior.
- JavaScript classes use prototypes behind the scenes.
- Use composition when inheritance does not fit the relationship.
14. Next Steps and Community
Try It Yourself: Build a small school staff management example. Add students, teachers, and principals. Use inheritance only for shared staff behavior.
Explore Further: Read the official MDN JavaScript Classes guide. It explains class syntax, constructors, inheritance, and related features.
Share Your Knowledge: Share your class design and code examples. Discuss alternative approaches and help other learners understand inheritance.
Keep practising, and build clean JavaScript applications with confidence.
Well explained, Harshitha! The article covers everything from basic classes to inheritance, method overriding and prototypes in a structured way. A very useful learning resource for JavaScript developers. Keep it up!