Objects, Arrays, and DestructuringLesson 3.5
ES6 classes in JavaScript: syntax, inheritance, and pitfalls
class declaration, constructor, instance methods, static methods, inheritance with extends, super keyword, private fields, class fields, instanceof
Class Syntax โ Cleaner Prototype Code
ES6 classes provide a clean syntax for creating objects with shared behavior. Under the hood they use prototypes โ the syntax is readable and familiar to developers from class-based languages, but the runtime model is still prototype chains.
Defining a Class
class Animal {
#name; // private field โ cannot be accessed outside class
constructor(name, sound) {
this.#name = name;
this.sound = sound;
}
speak() {
return `${this.#name} says ${this.sound}`;
}
static create(name, sound) {
return new Animal(name, sound);
}
}
const cat = new Animal("Cat", "meow");
cat.speak(); // "Cat says meow"
Animal.create("Dog", "woof"); // static โ called on the class
Inheritance with extends
class Dog extends Animal {
constructor(name) {
super(name, "woof"); // must call before using this
this.tricks = [];
}
learn(trick) {
this.tricks.push(trick);
return this; // method chaining
}
}
const dog = new Dog("Rex");
dog.learn("sit").learn("stay");
dog.speak(); // "Rex says woof"
dog instanceof Dog; // true
dog instanceof Animal; // true
Key Pitfalls
Always call super() before referencing this in a subclass constructor โ omitting it throws a ReferenceError. Private fields prefixed with # are truly private and inaccessible outside the class body, unlike naming conventions like _private.
