Beginner LevelJavaScript & TypeScript
How do JavaScript ES6 classes work (constructor, methods, extends, super)?
❓ Interview Prompt: Explain ES6 class syntax, constructors, instance methods, static methods, inheritance with extends, and super calls.
ES6 classes provide cleaner, standard syntactic sugar over JavaScript's existing prototype-based inheritance model.
Key Components:
•
`constructor()`: Special method invoked when instantiating via
new ClassName().•
Instance Methods: Defined directly in the class body; placed on
ClassName.prototype.•
Static Methods: Defined with
static keyword; called directly on the class (ClassName.method()), not instances.•
Inheritance (`extends` & `super`): Child classes inherit from parent classes. Child constructors must call
super() before accessing this.Code Implementation Example
javascript
class Vehicle {
constructor(make, speed) {
this.make = make;
this.speed = speed;
}
accelerate(amount) {
this.speed += amount;
return `${this.make} speed is now ${this.speed} km/h`;
}
static isVehicle(obj) {
return obj instanceof Vehicle;
}
}
// Inheriting from Vehicle
class Car extends Vehicle {
constructor(make, speed, doors) {
super(make, speed); // Calls parent constructor!
this.doors = doors;
}
}
const myCar = new Car('Toyota', 60, 4);
console.log(myCar.accelerate(20)); // "Toyota speed is now 80 km/h"
console.log(Vehicle.isVehicle(myCar)); // true💡Class inheritance hierarchy with extends, super constructor calls, and static utility methods.
🎯 Interview Key Takeaway
Classes are syntactic sugar over prototypal inheritance. Subclasses must invoke super() in constructors before using this.
#Classes#OOP#Inheritance#Beginner
Back to all JavaScript & TypeScript Questions→