OOP: Classes & Prototypes

🟨 JavaScript Lesson 11 Intermediate

JavaScript uses prototypical inheritance. ES6 introduced class syntax as syntactical sugar over prototypes to make code structure cleaner.

1 Prototypes vs. ES6 Classes (extends & super)

Every object in JavaScript has an internal link pointing to another object called its **Prototype**. When accessing a property or method, JS searches the object first. If not found, it traverses up the prototype chain.

The modern **class** syntax makes structure layouts clean, supporting constructors, methods, and parent inheritance using the `extends` and `super` keywords.

2 Class Declarations

Let's run a program declaring classes, inheriting methods, and overriding parent configurations:

JavaScript — ES6 Classes ▶ Run Code
class Person {
    constructor(name) {
        this.name = name;
    }
    
    speak() {
        console.log(`${this.name} makes a sound.`);
    }
}

// Inheriting from Person
class Programmer extends Person {
    constructor(name, lang) {
        super(name); // Call the parent class constructor
        this.lang = lang;
    }

    // Method Overriding
    speak() {
        console.log(`${this.name} writes code in ${this.lang}.`);
    }
}

const coder = new Programmer("Alice", "JavaScript");
coder.speak(); // Invokes child overridden method
3 Code Challenge
Challenge: Define a class called `Shape` with a constructor taking a shape name and a method `getArea()` returning 0. Create a subclass called `Square` extending Shape, which takes a side length parameter and overrides `getArea()` to return side * side. Instantiate `Square` and print its area.