JavaScript and TypeScript course Β· Module 2: Functions, Arrays and Objects
Prototypes and Prototypal Inheritance
In this lesson12
In Jurassic Park, managing the different dinosaur species effectively requires understanding the similarities between them and the ways traits can be inherited. JavaScript uses prototypes to implement inheritance - this is one of the most unique and powerful aspects of the language. Understanding prototypes and prototypal inheritance is key to writing efficient, flexible JavaScript code.
What Are Prototypes?
In JavaScript every object has an internal property called its prototype, which is a reference to another object. When we try to access a property of an object, JavaScript first checks whether the object itself has that property. If not, it checks the object's prototype, then the prototype's prototype, and so on, forming what is known as the prototype chain.
// We create a simple object
const dinosaur = {
species: "Tyrannosaurus",
makesSound: true,
roar() {
return "ROOOOAR!";
}
};
// We create a new object that inherits from the dinosaur object
const rex = Object.create(dinosaur);
rex.name = "Rex";
rex.age = 8;
// rex has access to its own properties
console.log(rex.name); // "Rex"
console.log(rex.age); // 8
// rex also has access to the properties and methods of dinosaur
console.log(rex.species); // "Tyrannosaurus"
console.log(rex.makesSound); // true
console.log(rex.roar()); // "ROOOOAR!"
// Let's check whether rex has its own 'species' property (it does not)
console.log(rex.hasOwnProperty('species')); // false
// But it does have its own 'name' property
console.log(rex.hasOwnProperty('name')); // trueIn the example above, rex has no species property of its own, but accessing rex.species works, because JavaScript looks for that property in the prototype of rex, which is the dinosaur object.
The Prototype Chain
Prototypes form a chain that JavaScript searches when we try to access a property. We call this mechanism the prototype chain.
// The basic ancestor object
const animal = {
isAlive: true,
eat() {
return `${this.name} is eating.`;
}
};
// A dinosaur object inheriting from animal
const dinosaur = Object.create(animal);
dinosaur.isExtinct = false;
dinosaur.roar = function() {
return `${this.name} roars!`;
};
// A specific dinosaur species inheriting from dinosaur
const tyrannosaurus = Object.create(dinosaur);
tyrannosaurus.name = "Tyrannosaurus";
tyrannosaurus.diet = "carnivore";
tyrannosaurus.length = 12; // meters
// tyrannosaurus has access to the properties of all the prototypes in the chain
console.log(tyrannosaurus.name); // "Tyrannosaurus" (own property)
console.log(tyrannosaurus.isExtinct); // false (from dinosaur)
console.log(tyrannosaurus.isAlive); // true (from animal)
console.log(tyrannosaurus.eat()); // "Tyrannosaurus is eating." (method from animal, this refers to tyrannosaurus)
console.log(tyrannosaurus.roar()); // "Tyrannosaurus roars!" (method from dinosaur)Constructors and Prototypes
In practice, prototypes are most often used with constructors and classes to implement inheritance in JavaScript.
Constructor Functions and Prototypes
Every constructor function has a prototype property, which is used as the prototype for objects created with that function and the new operator.
// Constructor function for Dinosaur
function Dinosaur(name, species, diet) {
this.name = name;
this.species = species;
this.diet = diet;
this.isExtinct = false;
}
// We add methods to the Dinosaur prototype
Dinosaur.prototype.roar = function() {
const volume = this.diet === "carnivore" ? "loudly" : "quietly";
return `${this.name} roars ${volume}!`;
};
Dinosaur.prototype.describe = function() {
return `${this.name} is a ${this.species} that is ${this.diet === "carnivore" ? "carnivorous" : "herbivorous"}.`;
};
// We create instances
const trex = new Dinosaur("Rex", "Tyrannosaurus", "carnivore");
const tricera = new Dinosaur("Trixie", "Triceratops", "herbivore");
console.log(trex.roar()); // "Rex roars loudly!"
console.log(tricera.roar()); // "Trixie roars quietly!"
console.log(trex.describe()); // "Rex is a Tyrannosaurus that is carnivorous."
// All instances share the same prototype methods
console.log(trex.roar === tricera.roar); // trueIn this example, the roar and describe methods are defined on the prototype of the Dinosaur constructor function. All instances created with new Dinosaur() share the same methods, which is much more efficient than defining these methods in the constructor separately for every instance.
Checking an Object's Prototype
We can check an object's prototype in several ways:
// Using Object.getPrototypeOf()
console.log(Object.getPrototypeOf(trex) === Dinosaur.prototype); // true
// Using __proto__ (a deprecated property, not recommended in production code)
console.log(trex.__proto__ === Dinosaur.prototype); // true
// Checking whether an object is an instance of a constructor
console.log(trex instanceof Dinosaur); // true
console.log(trex instanceof Object); // true (all objects inherit from Object.prototype)Inheritance Between Constructors
We can implement inheritance between constructor functions by linking their prototypes:
// Constructor function for Animal (base class)
function Animal(name) {
this.name = name;
this.isAlive = true;
}
Animal.prototype.eat = function(food) {
return `${this.name} eats ${food}.`;
};
Animal.prototype.sleep = function() {
return `${this.name} is sleeping.`;
};
// Constructor function for Dinosaur (derived class)
function Dinosaur(name, species, diet) {
// We call the base class constructor
Animal.call(this, name);
// We add properties specific to Dinosaur
this.species = species;
this.diet = diet;
this.isExtinct = false;
}
// We set the Dinosaur prototype so that it inherits from Animal.prototype
Dinosaur.prototype = Object.create(Animal.prototype);
// We restore the correct constructor property
Dinosaur.prototype.constructor = Dinosaur;
// We add methods specific to Dinosaur
Dinosaur.prototype.roar = function() {
const volume = this.diet === "carnivore" ? "loudly" : "quietly";
return `${this.name} roars ${volume}!`;
};
// We create a Dinosaur instance
const velociraptor = new Dinosaur("Blue", "Velociraptor", "carnivore");
// We have access to the methods from Animal
console.log(velociraptor.eat("meat")); // "Blue eats meat."
console.log(velociraptor.sleep()); // "Blue is sleeping."
// And to the methods specific to Dinosaur
console.log(velociraptor.roar()); // "Blue roars loudly!"
// We check the prototype chain
console.log(velociraptor instanceof Dinosaur); // true
console.log(velociraptor instanceof Animal); // true
console.log(velociraptor instanceof Object); // trueThis pattern for implementing inheritance between constructors is often called "pseudoclassical inheritance", because it emulates class-based inheritance in a language that was originally based on prototypes.
Multi-Level Inheritance
We can build multi-level inheritance hierarchies by linking prototype chains:
// Animal base class
function Animal(name) {
this.name = name;
this.isAlive = true;
}
Animal.prototype.breathe = function() {
return `${this.name} is breathing.`;
};
// Dinosaur class inheriting from Animal
function Dinosaur(name, period) {
Animal.call(this, name);
this.period = period;
this.extinct = true;
}
Dinosaur.prototype = Object.create(Animal.prototype);
Dinosaur.prototype.constructor = Dinosaur;
Dinosaur.prototype.roar = function() {
return `${this.name} roars!`;
};
// Theropod class inheriting from Dinosaur
function Theropod(name, period, speed) {
Dinosaur.call(this, name, period);
this.speed = speed; // km/h
this.bipedal = true;
}
Theropod.prototype = Object.create(Dinosaur.prototype);
Theropod.prototype.constructor = Theropod;
Theropod.prototype.run = function() {
return `${this.name} runs at a speed of ${this.speed} km/h!`;
};
// Tyrannosaurus class inheriting from Theropod
function Tyrannosaurus(name, size) {
Theropod.call(this, name, "Late Cretaceous", 30);
this.size = size;
this.teeth = 60;
}
Tyrannosaurus.prototype = Object.create(Theropod.prototype);
Tyrannosaurus.prototype.constructor = Tyrannosaurus;
Tyrannosaurus.prototype.bite = function() {
return `${this.name} bites with enormous force thanks to its ${this.teeth} teeth!`;
};
// We create a Tyrannosaurus instance
const rex = new Tyrannosaurus("Rex", "very large");
// We have access to the methods of all the prototypes in the chain
console.log(rex.breathe()); // "Rex is breathing." (from Animal)
console.log(rex.roar()); // "Rex roars!" (from Dinosaur)
console.log(rex.run()); // "Rex runs at a speed of 30 km/h!" (from Theropod)
console.log(rex.bite()); // "Rex bites with enormous force thanks to its 60 teeth!" (from Tyrannosaurus)
// We check the prototype chain
console.log(rex instanceof Tyrannosaurus); // true
console.log(rex instanceof Theropod); // true
console.log(rex instanceof Dinosaur); // true
console.log(rex instanceof Animal); // true
console.log(rex instanceof Object); // truePrototypes and Classes in ES6+
ES6 introduced the class syntax, which uses prototypes under the hood but offers a friendlier syntax, similar to classical object-oriented programming:
// Animal base class
class Animal {
constructor(name) {
this.name = name;
this.isAlive = true;
}
eat(food) {
return `${this.name} eats ${food}.`;
}
sleep() {
return `${this.name} is sleeping.`;
}
}
// Dinosaur class inheriting from Animal
class Dinosaur extends Animal {
constructor(name, species, diet) {
super(name); // Calling the base class constructor
this.species = species;
this.diet = diet;
this.isExtinct = false;
}
roar() {
const volume = this.diet === "carnivore" ? "loudly" : "quietly";
return `${this.name} roars ${volume}!`;
}
// We override the eat method from the base class
eat(food) {
if (this.diet === "carnivore" && food === "meat") {
return `${this.name} hungrily devours ${food}!`;
} else if (this.diet === "herbivore" && food === "plants") {
return `${this.name} calmly nibbles on ${food}.`;
} else {
return `${this.name} is not interested in eating ${food}.`;
}
}
}
// Velociraptor derived class inheriting from Dinosaur
class Velociraptor extends Dinosaur {
constructor(name, speed) {
super(name, "Velociraptor", "carnivore");
this.speed = speed;
this.packHunter = true;
}
hunt() {
return `${this.name} hunts in a pack at a speed of ${this.speed} km/h!`;
}
}
// We create instances
const blue = new Velociraptor("Blue", 70);
console.log(blue.eat("meat")); // "Blue hungrily devours meat!"
console.log(blue.sleep()); // "Blue is sleeping."
console.log(blue.roar()); // "Blue roars loudly!"
console.log(blue.hunt()); // "Blue hunts in a pack at a speed of 70 km/h!"
// We check the prototype chain
console.log(blue instanceof Velociraptor); // true
console.log(blue instanceof Dinosaur); // true
console.log(blue instanceof Animal); // true
console.log(blue instanceof Object); // trueThe class syntax in ES6 is just "syntactic sugar" over the existing prototype mechanism in JavaScript. Under the hood, JavaScript still uses prototypes to implement inheritance.
Multiple Inheritance and Mixins
JavaScript does not directly support multiple inheritance (inheriting from several classes at once), but we can use the "mixins" pattern to achieve a similar effect:
// Base class
class Dinosaur {
constructor(name, species) {
this.name = name;
this.species = species;
}
roar() {
return `${this.name} roars!`;
}
}
// Mixin for carnivore behavior
const CarnivoreMixin = {
hunt(prey) {
return `${this.name} hunts ${prey}!`;
},
bite() {
return `${this.name} bites with great force!`;
}
};
// Mixin for pack hunting behavior
const PackHunterMixin = {
coordinateAttack() {
return `${this.name} coordinates the pack's attack!`;
},
communicateWithPack() {
return `${this.name} communicates with the other members of the pack.`;
}
};
// Mixin for territorial behavior
const TerritorialMixin = {
markTerritory() {
return `${this.name} marks its territory.`;
},
defendTerritory(intruder) {
return `${this.name} defends its territory against ${intruder}!`;
}
};
// Function that applies mixins to a class
function applyMixins(targetClass, ...mixins) {
mixins.forEach(mixin => {
Object.getOwnPropertyNames(mixin).forEach(name => {
if (name !== 'constructor') {
targetClass.prototype[name] = mixin[name];
}
});
});
}
// Velociraptor class with several mixins
class Velociraptor extends Dinosaur {
constructor(name) {
super(name, "Velociraptor");
this.diet = "carnivore";
this.speed = 70; // km/h
}
}
// We apply the mixins to Velociraptor
applyMixins(Velociraptor, CarnivoreMixin, PackHunterMixin, TerritorialMixin);
// We create a Velociraptor instance
const blue = new Velociraptor("Blue");
// Now blue has access to methods from different mixins
console.log(blue.roar()); // "Blue roars!" (from Dinosaur)
console.log(blue.hunt("Gallimimus")); // "Blue hunts Gallimimus!" (from CarnivoreMixin)
console.log(blue.bite()); // "Blue bites with great force!" (from CarnivoreMixin)
console.log(blue.coordinateAttack()); // "Blue coordinates the pack's attack!" (from PackHunterMixin)
console.log(blue.defendTerritory("Tyrannosaurus")); // "Blue defends its territory against Tyrannosaurus!" (from TerritorialMixin)Mixins let you "mix in" functionality from different sources without having to use multiple inheritance, which JavaScript does not formally support.
Object.prototype
All objects in JavaScript ultimately inherit from Object.prototype. It contains many useful methods, such as toString(), hasOwnProperty(), valueOf(), etc.
const dino = { name: "Rex" };
// dino inherits methods from Object.prototype
console.log(dino.toString()); // "[object Object]"
console.log(dino.hasOwnProperty("name")); // true
console.log(dino.hasOwnProperty("age")); // false
// We can override methods from Object.prototype
dino.toString = function() {
return `Dinosaur: ${this.name}`;
};
console.log(dino.toString()); // "Dinosaur: Rex"Prototypal Inheritance in Practice: The Jurassic Park Dinosaur System
Below is an example of a more complex dinosaur management system that uses prototypal inheritance:
// Base class for all creatures in the park
class Creature {
constructor(name, age) {
this.name = name;
this.age = age;
this.health = 100;
this.alive = true;
}
eat(food) {
this.health = Math.min(100, this.health + 10);
return `${this.name} eats ${food}. Health: ${this.health}%`;
}
sleep() {
this.health = Math.min(100, this.health + 5);
return `${this.name} is sleeping. Health: ${this.health}%`;
}
damage(amount) {
this.health = Math.max(0, this.health - amount);
if (this.health === 0 && this.alive) {
this.alive = false;
return `${this.name} is dead!`;
}
return `${this.name} takes ${amount} damage. Remaining health: ${this.health}%`;
}
}
// Class for dinosaurs, inheriting from Creature
class Dinosaur extends Creature {
constructor(name, species, age, diet) {
super(name, age);
this.species = species;
this.diet = diet;
this.containmentLevel = this.calculateContainmentLevel();
}
calculateContainmentLevel() {
if (this.diet === "carnivore") {
return this.age > 5 ? "Maximum" : "High";
} else {
return this.age > 10 ? "Medium" : "Standard";
}
}
roar() {
const volume = this.diet === "carnivore" ? "loudly" : "quietly";
return `${this.name} roars ${volume}!`;
}
getStatus() {
return `
Dinosaur: ${this.name} (${this.species})
Age: ${this.age} years
Diet: ${this.diet === "carnivore" ? "Carnivorous" : "Herbivorous"}
Health: ${this.health}%
Status: ${this.alive ? "Alive" : "Dead"}
Security level: ${this.containmentLevel}
`;
}
}
// Class for carnivorous dinosaurs (predators)
class Carnivore extends Dinosaur {
constructor(name, species, age, attackPower) {
super(name, species, age, "carnivore");
this.attackPower = attackPower;
this.huntingSuccess = 0.7; // 70% chance of a successful hunt
}
hunt(prey) {
if (!this.alive) return `${this.name} is dead and cannot hunt.`;
if (!prey.alive) return `${prey.name} is already dead.`;
const huntSuccess = Math.random() < this.huntingSuccess;
if (huntSuccess) {
const damage = Math.floor(this.attackPower * (0.7 + Math.random() * 0.6)); // 70-130% of attack power
const result = prey.damage(damage);
this.eat("meat");
return `${this.name} successfully hunts ${prey.name}! ${result}`;
} else {
return `${this.name} tries to hunt ${prey.name}, but fails.`;
}
}
clawAttack(target) {
if (!this.alive) return `${this.name} is dead and cannot attack.`;
if (!target.alive) return `${target.name} is already dead.`;
const damage = Math.floor(this.attackPower * 0.6);
const result = target.damage(damage);
return `${this.name} attacks ${target.name} with its claws! ${result}`;
}
biteAttack(target) {
if (!this.alive) return `${this.name} is dead and cannot attack.`;
if (!target.alive) return `${target.name} is already dead.`;
const damage = Math.floor(this.attackPower * 1.2);
const result = target.damage(damage);
return `${this.name} bites ${target.name}! ${result}`;
}
}
// Class for herbivorous dinosaurs
class Herbivore extends Dinosaur {
constructor(name, species, age, defenseRating) {
super(name, species, age, "herbivore");
this.defenseRating = defenseRating;
this.fleeSuccess = 0.6; // 60% chance of a successful escape
}
grazeVegetation() {
if (!this.alive) return `${this.name} is dead and cannot eat.`;
this.health = Math.min(100, this.health + 15);
return `${this.name} nibbles on plants. Health rises to ${this.health}%.`;
}
flee(predator) {
if (!this.alive) return `${this.name} is dead and cannot flee.`;
const escapeSuccess = Math.random() < this.fleeSuccess;
if (escapeSuccess) {
this.health = Math.max(0, this.health - 5); // Fleeing costs energy
return `${this.name} successfully escapes from ${predator.name}!`;
} else {
return `${this.name} tries to escape from ${predator.name}, but fails.`;
}
}
// Defensive method - reduces the damage taken
damage(amount) {
// Herbivores take less damage thanks to defenseRating
const reducedDamage = Math.max(0, amount - this.defenseRating);
return super.damage(reducedDamage);
}
}
// Specific dinosaur species
class Tyrannosaurus extends Carnivore {
constructor(name, age) {
super(name, "Tyrannosaurus Rex", age, 35);
this.intimidationFactor = 9;
this.territorialRange = 5; // km
}
intimidate(target) {
return `${this.name} lets out a deafening roar that terrifies ${target.name}!`;
}
// We override the roar method
roar() {
return `${this.name} lets out a mighty, deafening roar that carries for kilometers!`;
}
}
class Velociraptor extends Carnivore {
constructor(name, age) {
super(name, "Velociraptor", age, 20);
this.speed = 70; // km/h
this.intelligence = 9;
this.packHunting = true;
}
coordinateAttack(targets) {
if (!Array.isArray(targets) || targets.length < 2) {
return `${this.name} needs at least two targets to coordinate an attack.`;
}
let results = `${this.name} coordinates a pack attack on ${targets.map(t => t.name).join(', ')}!\n`;
targets.forEach(target => {
const damage = Math.floor(this.attackPower * 1.5); // Boosted pack attack
results += target.damage(damage) + '\n';
});
return results;
}
ambush(target) {
const damage = Math.floor(this.attackPower * 2); // Double damage from an ambush
const result = target.damage(damage);
return `${this.name} ambushes ${target.name}! ${result}`;
}
}
class Triceratops extends Herbivore {
constructor(name, age) {
super(name, "Triceratops", age, 25);
this.hornStrength = 30;
}
chargeAttack(target) {
const damage = this.hornStrength + Math.floor(Math.random() * 10);
const result = target.damage(damage);
return `${this.name} charges at ${target.name} with its horns! ${result}`;
}
defendFromAttack(attacker) {
const counterDamage = Math.floor(this.hornStrength * 0.5);
const result = attacker.damage(counterDamage);
return `${this.name} defends itself against ${attacker.name} using its horns! ${result}`;
}
}
class Brachiosaurus extends Herbivore {
constructor(name, age) {
super(name, "Brachiosaurus", age, 15);
this.height = 13; // meters
this.tailLength = 9; // meters
}
reachHighVegetation() {
this.health = Math.min(100, this.health + 20);
return `${this.name} stretches its long neck to reach the leaves of tall trees. Health rises to ${this.health}%.`;
}
tailWhip(target) {
const damage = Math.floor(this.tailLength * 2);
const result = target.damage(damage);
return `${this.name} strikes ${target.name} with its enormous tail! ${result}`;
}
}
// Jurassic Park simulation
function runJurassicParkSimulation() {
console.log("=== JURASSIC PARK SIMULATION ===\n");
// Creating the dinosaurs
const rex = new Tyrannosaurus("Rex", 8);
const blue = new Velociraptor("Blue", 4);
const delta = new Velociraptor("Delta", 4);
const trixie = new Triceratops("Trixie", 12);
const bronty = new Brachiosaurus("Bronty", 25);
// Displaying information about the dinosaurs
console.log(rex.getStatus());
console.log(blue.getStatus());
console.log(trixie.getStatus());
console.log(bronty.getStatus());
console.log("\n=== DINOSAUR INTERACTIONS ===\n");
// Interactions between dinosaurs
console.log(rex.roar());
console.log(blue.roar());
console.log(trixie.grazeVegetation());
console.log(bronty.reachHighVegetation());
console.log("\n=== DUEL: REX VS TRIXIE ===\n");
console.log(rex.intimidate(trixie));
console.log(trixie.flee(rex));
console.log(rex.hunt(trixie));
console.log(trixie.defendFromAttack(rex));
console.log(rex.biteAttack(trixie));
console.log("\n=== VELOCIRAPTOR PACK HUNT ===\n");
console.log(blue.coordinateAttack([trixie, bronty]));
console.log(delta.ambush(bronty));
console.log(bronty.tailWhip(delta));
console.log("\n=== DINOSAUR STATUS AFTER THE INTERACTIONS ===\n");
console.log(rex.getStatus());
console.log(blue.getStatus());
console.log(delta.getStatus());
console.log(trixie.getStatus());
console.log(bronty.getStatus());
}
// Running the simulation
runJurassicParkSimulation();Prototypal Inheritance vs Classical Inheritance
Prototypal inheritance in JavaScript differs from classical inheritance in other object-oriented languages:
- Dynamism - prototypes can be modified while the program is running, whereas classes are usually static.
- The prototype chain - properties are looked up along the prototype chain, whereas in classical inheritance methods are resolved through the class hierarchy.
- No classes (before ES6) - JavaScript traditionally had no formal concept of classes, only constructor functions and prototypes.
- Single inheritance - JavaScript supports only single inheritance (each object has just one prototype), whereas some languages support multiple inheritance.
Best Practices When Working with Prototypes
- Understand the mechanism - it is important to understand how the prototype chain works in order to use inheritance effectively.
- Use classes (ES6+) - for most use cases the class syntax is more readable and easier to maintain.
- Avoid modifying built-in prototypes - modifying the prototypes of built-in objects (e.g. Object.prototype, Array.prototype) can lead to unexpected conflicts.
- Use Object.create() for inheritance - when you take the traditional approach, Object.create() is a clean way to implement prototypal inheritance.
- Composition over inheritance - sometimes it is better to use composition (combining objects) instead of deep inheritance, to avoid problems with the hierarchy.
Summary
Prototypes and prototypal inheritance are fundamental concepts in JavaScript. Even when we use the modern class syntax (ES6+), it is important to understand the underlying prototype mechanism in order to make full use of the language. In our Jurassic Park, prototypal inheritance helps us model different types of dinosaurs and their behaviors in a consistent, efficient way.
The main concepts we covered are:
- Prototypes - the mechanism that lets objects inherit properties and methods from other objects.
- The prototype chain - a sequence of objects linked through their prototypes, which JavaScript searches when it tries to access a property.
- Constructor functions and prototypes - the traditional way of implementing inheritance in JavaScript.
- ES6+ classes - a modern syntax for inheritance, built on the prototype mechanism.
- Mixins - a way to combine functionality from different sources.
Understanding prototypes and inheritance in JavaScript is the key to writing efficient, well-organized code that can model complex relationships between objects, such as those in our virtual Jurassic Park.
Code for this lesson: index.js
// Prototypes and inheritance - Jurassic Park
console.log("Prototypes and Inheritance");
console.log("Advanced OOP concepts in JavaScript\n");
// ===========================================
// 1. PROTOTYPE BASICS
// ===========================================
console.log("=== 1. What are prototypes? ===");
function Dinosaur(name, species) {
this.name = name;
this.species = species;
}
// Adding methods to the prototype
Dinosaur.prototype.roar = function() {
return `${this.name} says: ROAARRR!`;
};
Dinosaur.prototype.getInfo = function() {
return `${this.name} (${this.species})`;
};
const trex = new Dinosaur("Rexy", "T-Rex");
const raptor = new Dinosaur("Blue", "Velociraptor");
console.log("\n", trex.getInfo());
console.log(" ", trex.roar());
console.log("\n", raptor.getInfo());
console.log(" ", raptor.roar());
// Checking the prototype
console.log("\nChecking the prototype:");
console.log(` trex.__proto__ === Dinosaur.prototype: ${trex.__proto__ === Dinosaur.prototype}`);
console.log(` raptor.constructor === Dinosaur: ${raptor.constructor === Dinosaur}`);
// ===========================================
// 2. PROTOTYPE CHAIN
// ===========================================
console.log("\n=== 2. Prototype chain ===");
console.log("\nPrototype chain for trex:");
console.log(` trex β Dinosaur.prototype β Object.prototype β null`);
console.log("\nMethods accessible via the chain:");
console.log(` trex.getInfo() (from Dinosaur.prototype): ${trex.getInfo()}`);
console.log(` trex.toString() (from Object.prototype): ${trex.toString()}`);
console.log(` trex.hasOwnProperty('name'): ${trex.hasOwnProperty('name')}`);
// Checking in the chain
console.log("\ninstanceof:");
console.log(` trex instanceof Dinosaur: ${trex instanceof Dinosaur}`);
console.log(` trex instanceof Object: ${trex instanceof Object}`);
// ===========================================
// 3. PROTOTYPAL INHERITANCE
// ===========================================
console.log("\n=== 3. Prototypal inheritance ===");
function Animal(name, age) {
this.name = name;
this.age = age;
}
Animal.prototype.breathe = function() {
return `${this.name} breathes`;
};
Animal.prototype.getAge = function() {
return `${this.name} is ${this.age} years old`;
};
// Carnivore inherits from Animal
function Carnivore(name, age, huntingSkill) {
Animal.call(this, name, age); // Call the parent constructor
this.huntingSkill = huntingSkill;
}
// Setting up inheritance
Carnivore.prototype = Object.create(Animal.prototype);
Carnivore.prototype.constructor = Carnivore;
// Adding own methods
Carnivore.prototype.hunt = function() {
return `${this.name} hunts (skill: ${this.huntingSkill}/10)`;
};
Carnivore.prototype.roar = function() {
return `${this.name} roars: ROAARRR!`;
};
const rex = new Carnivore("Rex", 8, 10);
console.log("\nCarnivore (inherits from Animal):");
console.log(` ${rex.getAge()}`); // From Animal
console.log(` ${rex.breathe()}`); // From Animal
console.log(` ${rex.hunt()}`); // Own method
console.log(` ${rex.roar()}`); // Own method
// ===========================================
// 4. ES6 CLASSES (SYNTACTIC SUGAR)
// ===========================================
console.log("\n=== 4. ES6 Classes ===");
class DinoBase {
constructor(name, species, age) {
this.name = name;
this.species = species;
this.age = age;
}
getInfo() {
return `${this.name} (${this.species}) - ${this.age} years`;
}
breathe() {
return `${this.name} breathes`;
}
}
class CarnivoreClass extends DinoBase {
constructor(name, species, age, huntingSkill) {
super(name, species, age);
this.huntingSkill = huntingSkill;
this.type = "Carnivore";
}
hunt() {
return `${this.name} hunts (skill: ${this.huntingSkill}/10)`;
}
roar() {
return `${this.name} roars: ROAARRR!`;
}
// Method override from the base class
getInfo() {
return `${super.getInfo()} | Type: ${this.type}`;
}
}
class HerbivoreClass extends DinoBase {
constructor(name, species, age, plantPreference) {
super(name, species, age);
this.plantPreference = plantPreference;
this.type = "Herbivore";
}
eat() {
return `${this.name} eats ${this.plantPreference}`;
}
graze() {
return `${this.name} peacefully grazes`;
}
getInfo() {
return `${super.getInfo()} | Type: ${this.type}`;
}
}
const rexy = new CarnivoreClass("Rexy", "T-Rex", 8, 10);
const trike = new HerbivoreClass("Trike", "Triceratops", 7, "ferns");
console.log("\nCarnivore:");
console.log(` ${rexy.getInfo()}`);
console.log(` ${rexy.breathe()}`);
console.log(` ${rexy.hunt()}`);
console.log(` ${rexy.roar()}`);
console.log("\nHerbivore:");
console.log(` ${trike.getInfo()}`);
console.log(` ${trike.breathe()}`);
console.log(` ${trike.eat()}`);
console.log(` ${trike.graze()}`);
// ===========================================
// 5. MULTI-LEVEL INHERITANCE
// ===========================================
console.log("\n=== 5. Multi-level inheritance ===");
class LivingBeing {
constructor(name) {
this.name = name;
}
live() {
return `${this.name} is alive`;
}
}
class Reptile extends LivingBeing {
constructor(name, scaleType) {
super(name);
this.scaleType = scaleType;
}
shedSkin() {
return `${this.name} sheds its skin`;
}
}
class PrehistoricReptile extends Reptile {
constructor(name, scaleType, period) {
super(name, scaleType);
this.period = period;
this.extinct = true;
}
getHistory() {
return `${this.name} lived in the ${this.period} period`;
}
}
const velociraptor = new PrehistoricReptile("Blue", "small", "Cretaceous");
console.log("\nVelociraptor (3 levels of inheritance):");
console.log(` ${velociraptor.live()}`); // From LivingBeing
console.log(` ${velociraptor.shedSkin()}`); // From Reptile
console.log(` ${velociraptor.getHistory()}`); // From PrehistoricReptile
console.log("\ninstanceof (multi-level):");
console.log(` instanceof PrehistoricReptile: ${velociraptor instanceof PrehistoricReptile}`);
console.log(` instanceof Reptile: ${velociraptor instanceof Reptile}`);
console.log(` instanceof LivingBeing: ${velociraptor instanceof LivingBeing}`);
console.log(` instanceof Object: ${velociraptor instanceof Object}`);
// ===========================================
// 6. MIXINS (COMPOSITION OVER INHERITANCE)
// ===========================================
console.log("\n=== 6. Mixins - composition instead of inheritance ===");
// Mixin for flying capabilities
const FlyingMixin = {
fly() {
return `${this.name} flies at a speed of ${this.flyingSpeed} km/h`;
},
land() {
return `${this.name} lands`;
}
};
// Mixin for swimming capabilities
const SwimmingMixin = {
swim() {
return `${this.name} swims`;
},
dive() {
return `${this.name} dives`;
}
};
// Helper function for adding mixins
function addMixins(targetClass, ...mixins) {
mixins.forEach(mixin => {
Object.assign(targetClass.prototype, mixin);
});
}
class Pteranodon {
constructor(name, flyingSpeed) {
this.name = name;
this.flyingSpeed = flyingSpeed;
}
roar() {
return `${this.name} screeches: SCREECH!`;
}
}
class Mosasaurus {
constructor(name) {
this.name = name;
}
roar() {
return `${this.name} roars underwater: ROAARRR!`;
}
}
// Adding mixins
addMixins(Pteranodon, FlyingMixin);
addMixins(Mosasaurus, SwimmingMixin);
const ptero = new Pteranodon("Pterry", 80);
const mosa = new Mosasaurus("Mosa");
console.log("\nPteranodon (with the flying mixin):");
console.log(` ${ptero.roar()}`);
console.log(` ${ptero.fly()}`);
console.log(` ${ptero.land()}`);
console.log("\nMosasaurus (with the swimming mixin):");
console.log(` ${mosa.roar()}`);
console.log(` ${mosa.swim()}`);
console.log(` ${mosa.dive()}`);
// ===========================================
// 7. COMPLEX EXAMPLE
// ===========================================
console.log("\n=== 7. Ecosystem simulation - complex example ===");
class Ecosystem {
constructor(name) {
this.name = name;
this.creatures = [];
}
addCreature(creature) {
this.creatures.push(creature);
console.log(`Added ${creature.name} to ecosystem ${this.name}`);
}
simulate() {
console.log(`\n============================================================`);
console.log(`ECOSYSTEM SIMULATION: ${this.name}`);
console.log("=".repeat(60));
console.log(`\nTotal creatures: ${this.creatures.length}`);
const carnivores = this.creatures.filter(c => c.type === "Carnivore");
const herbivores = this.creatures.filter(c => c.type === "Herbivore");
console.log(` Carnivores: ${carnivores.length}`);
console.log(` Herbivores: ${herbivores.length}`);
console.log("\nCreature activities:");
this.creatures.forEach((creature, i) => {
console.log(`\n ${i + 1}. ${creature.getInfo()}`);
console.log(` ${creature.breathe()}`);
if (creature.hunt) {
console.log(` ${creature.hunt()}`);
console.log(` ${creature.roar()}`);
}
if (creature.eat) {
console.log(` ${creature.eat()}`);
console.log(` ${creature.graze()}`);
}
});
this.showFoodChain();
}
showFoodChain() {
console.log("\nFood chain:");
const carnivores = this.creatures.filter(c => c.type === "Carnivore");
const herbivores = this.creatures.filter(c => c.type === "Herbivore");
console.log(` Plants β Herbivores (${herbivores.map(h => h.name).join(", ")})`);
console.log(` Herbivores β Carnivores (${carnivores.map(c => c.name).join(", ")})`);
}
}
// Creating the ecosystem
const jurassicEcosystem = new Ecosystem("Jurassic Park");
// Adding creatures
jurassicEcosystem.addCreature(new CarnivoreClass("Rexy", "T-Rex", 8, 10));
jurassicEcosystem.addCreature(new CarnivoreClass("Blue", "Velociraptor", 5, 9));
jurassicEcosystem.addCreature(new HerbivoreClass("Trike", "Triceratops", 7, "ferns"));
jurassicEcosystem.addCreature(new HerbivoreClass("Stego", "Stegosaurus", 6, "plants"));
jurassicEcosystem.addCreature(new CarnivoreClass("Delta", "Velociraptor", 5, 8));
// Run the simulation
jurassicEcosystem.simulate();
console.log("\nCongratulations! You've mastered prototypes and inheritance!");Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What happens when you try to access a property that the object doesn't have?
2. What does the Object.create(proto) method do?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps of searching for a property in the prototype chain: