ES6 Classes & Inheritance
ES6 classes are syntactic sugar over prototypes — a cleaner way to create objects and implement inheritance. They look like classes in other languages but work via JavaScript's prototype system under the hood.
Classes & Inheritance
- class — Clean syntax for constructor functions: class User { constructor(name) { this.name = name; } }
- constructor() — Called when creating new instance. Initialize properties here
- Methods — Defined inside class body. Automatically on the prototype
- extends — Inheritance: class Admin extends User { }. Admin inherits User's methods
- super() — Call parent constructor: super(name). Must be first line in child constructor
- static — Class-level methods: User.count. Not on instances, on the class itself
Classes Code
// ES6 Class
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
greet() {
return `Hello, I'm ${this.name}`;
}
getEmail() {
return this.email;
}
}
const alice = new User("Alice", "alice@email.com");
console.log(alice.greet()); // "Hello, I'm Alice"
// Inheritance with extends
class Admin extends User {
constructor(name, email, level) {
super(name, email); // call parent constructor FIRST
this.level = level;
}
// Override parent method
greet() {
return `${super.greet()} — Admin Level ${this.level}`;
}
ban(user) {
return `${this.name} banned ${user.name}`;
}
}
const admin = new Admin("Bob", "bob@email.com", 5);
console.log(admin.greet()); // "Hello, I'm Bob — Admin Level 5"
console.log(admin.getEmail()); // "bob@email.com" (inherited)
console.log(admin.ban(alice)); // "Bob banned Alice"
// instanceof
console.log(admin instanceof Admin); // true
console.log(admin instanceof User); // true (inheritance)Tip
Tip
Use super.methodName() to call the parent's version of an overridden method. This lets you extend behavior rather than replace it: greet() { return super.greet() + ' — Admin'; } combines parent and child functionality.
Classes are syntactic sugar over prototypes.
Common Mistake
Warning
Forgetting to call super() in a child constructor. If your class extends another and has a constructor, you MUST call super() before using 'this'. Otherwise you get: ReferenceError: Must call super constructor before accessing 'this'.
Practice Task
Note
Build a class hierarchy: (1) Create a Shape base class with name and color. (2) Extend it with Circle (add radius, area getter) and Rectangle (add width, height, area getter). (3) Override toString() in each. (4) Test instanceof for all.
Quick Quiz
Key Takeaways
- ES6 classes are syntactic sugar over prototypes — a cleaner way to create objects and implement inheritance.
- class — Clean syntax for constructor functions: class User { constructor(name) { this.name = name; } }
- constructor() — Called when creating new instance. Initialize properties here
- Methods — Defined inside class body. Automatically on the prototype