Module 6: Modern JavaScript, OOP, and Data
Classes, Constructors, and Inheritance
Model related objects with classes, instance methods, and safe inheritance.
A class defines a constructor and methods shared by instances. The new operator creates an instance, calls the constructor, and connects the instance to the class's prototype.
class Course {
constructor(title, level) {
this.title = title;
this.level = level;
}
describe() {
return `${this.title} (${this.level})`;
}
}
const javascript = new Course("JavaScript", "Beginner");
console.log(javascript.describe());
Methods are typically defined on the prototype rather than copied as a new function onto every instance. Class bodies run in strict mode. A class declaration cannot be used before it is initialized.
Inheritance#
Use extends when a subtype genuinely can be used anywhere its parent type is expected. In a derived constructor, call super(...) before accessing this.
class VideoCourse extends Course {
constructor(title, level, durationMinutes) {
super(title, level);
this.durationMinutes = durationMinutes;
}
}
A subclass can override inherited methods. Prefer composition when one object simply needs to use another object's behaviour; inheritance can otherwise create tight coupling.
Private fields#
Class private fields use a # prefix and cannot be accessed from outside the class body:
class Counter {
#value = 0;
increment() { this.#value += 1; }
read() { return this.#value; }
}
Practice#
Create a User class and a specialized AdminUser only if the subtype relationship makes sense. Explain why composition could be preferable in another design.