Prototypal Inheritance
While the class keyword was introduced in modern JavaScript (ES6) to make Object-Oriented Programming easier to write, classes are not actually the underlying mechanism for inheritance in JavaScript.
They are merely “syntactic sugar” layered over JavaScript’s true inheritance model: Prototypes.
The Prototype Model
Every object in JavaScript has an internal link to another object called its prototype. When an object “inherits” from another object, it simply means that its parent is marked as its prototype. This is called prototypal inheritance.
You can explicitly create a new object with a specific prototype using the built-in Object.create() method.
// Define a parent object (the prototype)
const pureTitan = {
name: "Eren's mom",
speak() {
console.log("*titan noises*");
},
};
// Create a child object inheriting from pureTitan
const beastTitan = Object.create(pureTitan);
// The child does not have its own 'name' property yet,
// so it looks up the chain and uses the parent's property.
console.log(beastTitan.name); // Output: "Eren's mom"
Modifying the Child
Once the child object is created, you can assign it entirely new properties or override the ones it inherited.
// Override the inherited property
beastTitan.name = "Zeke";
// Add new behavior
beastTitan.speak = function () {
console.log(`${this.name} says, "I'm the Beast Titan"`);
};
beastTitan.speak();
// Output: Zeke says, "I'm the Beast Titan"
// The parent object remains completely unaffected
pureTitan.speak();
// Output: *titan noises*