JavaScript and TypeScript course · Module 3: Classes and OOP
ES6 Class Syntax
In this lesson8
Welcome back to Jurassic Park! While working on our park full of dinosaurs, we'll need a way to organize our code. ES6 classes are the perfect tool that will allow us to model various aspects of our park - from the dinosaurs themselves, through enclosures, to security systems.
What are ES6 classes?
Classes introduced in ES6 (ECMAScript 2015) provide object-oriented syntax for JavaScript. Although JavaScript has always been a prototype-based language, ES6 classes offer a cleaner, more intuitive syntax for creating objects and managing inheritance.
In the context of our Jurassic Park, classes allow us to define "blueprints" for the different types of objects we will create.
Basic class syntax
Let's define our first class for the dinosaurs in the park:
class Dinosaur {
// Class body
}This simple declaration creates the Dinosaur class. It's like a template we'll use to create specific dinosaur specimens.
Declaring class properties
Dinosaurs in our park have various characteristics - species, weight, diet, etc. We can define these properties in our class:
class Dinosaur {
species; // Dinosaur species
weight; // Weight in kilograms
diet; // Diet type: 'carnivore', 'herbivore', 'omnivore'
enclosureId; // ID of the enclosure it's kept in
isActive = true; // Whether the dinosaur is active (default true)
}Although declaring properties like this isn't required in JavaScript, it's good practice, especially when using TypeScript, because it helps with documentation and typing of our class.
Creating class instances
To create a specific dinosaur based on our class, we use the new keyword:
// Creating a new T-Rex
const rex = new Dinosaur();
// Assigning properties
rex.species = 'Tyrannosaurus Rex';
rex.weight = 8000;
rex.diet = 'carnivore';
rex.enclosureId = 'T-REX-01';This way we created an instance of the Dinosaur class and set its properties. Every dinosaur we create will have its own set of these properties.
Classes as functions
In JavaScript, classes are a special type of function. Under the hood, when we declare a class, JavaScript creates a new constructor function.
// These two declarations work similarly (though not identically):
// Using ES6 class
class Dinosaur {
//
}
// Using a constructor function (older method)
function Dinosaur() {
//
}However, ES6 classes offer much cleaner syntax and additional features such as inheritance, which are harder to implement using simple constructor functions.
Classes as types in TypeScript
If we're working with TypeScript, we can also use classes as types:
class Dinosaur {
species: string;
weight: number;
diet: 'carnivore' | 'herbivore' | 'omnivore';
enclosureId: string;
isActive: boolean = true;
}
// Function that takes a dinosaur as a parameter
function feedDinosaur(dino: Dinosaur) {
console.log(`Feeding ${dino.species} in enclosure ${dino.enclosureId}`);
}
const rex = new Dinosaur();
rex.species = 'Tyrannosaurus Rex';
// ... set other properties
feedDinosaur(rex); // Works!
feedDinosaur({ species: 'Fake Dino' }); // Error - missing required propertiesIn this example, TypeScript ensures that only objects conforming to the Dinosaur type can be passed to the feedDinosaur function.
Private class fields
In newer versions of JavaScript (and in TypeScript) we can define private class fields using the # symbol. Private fields are only accessible inside the class where they were declared, which helps with encapsulation:
class Dinosaur {
species;
weight;
#healthStatus; // Private field - cannot be accessed from outside the class
checkHealth() {
// Method can access the private field
return this.#healthStatus;
}
updateHealth(status) {
this.#healthStatus = status;
}
}
const raptor = new Dinosaur();
raptor.updateHealth('Excellent');
console.log(raptor.checkHealth()); // 'Excellent'
// Error - cannot directly access a private field
// console.log(raptor.#healthStatus);Private fields are a great way to hide implementation details and prevent incorrect use of our classes.
Summary
ES6 classes are a powerful way to organize code in JavaScript. In our Jurassic Park we will use classes to model various aspects of the park, from dinosaurs to security systems and attractions. In the next step we'll look at constructors and methods, which will add behaviors to our classes.
Code for this lesson: index.js
// ES6 Classes in Jurassic Park
console.log("Welcome to the Jurassic Park management system!");
console.log("We use ES6 classes to model our park\n");
// ===========================================
// 1. Basic Dinosaur class
// ===========================================
console.log("=== 1. Basic Dinosaur class ===");
class Dinosaur {
// Property declarations (ES6+)
species;
weight;
diet;
enclosureId;
isActive = true; // Default value
// Method displaying information
getInfo() {
return `${this.species} weighs ${this.weight}kg and is ${this.diet}`;
}
// Sound production method
makeSound() {
return `${this.species} makes a sound!`;
}
// Feeding method
feed() {
if (!this.isActive) {
return `${this.species} is sleeping and cannot eat`;
}
return `Feeding ${this.species}. Dinosaur is happy!`;
}
}
// Creating an instance without a constructor
const rex = new Dinosaur();
rex.species = 'Tyrannosaurus Rex';
rex.weight = 8000;
rex.diet = 'carnivore';
rex.enclosureId = 'ENC-001';
console.log("Rex info:", rex.getInfo());
console.log("Rex sound:", rex.makeSound());
console.log("Feeding Rex:", rex.feed());
// ===========================================
// 2. Class with constructor
// ===========================================
console.log("\n=== 2. Class with constructor ===");
class DinosaurAdvanced {
constructor(species, weight, diet, enclosureId) {
this.species = species;
this.weight = weight;
this.diet = diet;
this.enclosureId = enclosureId;
this.isActive = true;
this.energy = 100;
this.lastFed = new Date();
console.log(`Created new dinosaur: ${species}`);
}
// Instance methods
getInfo() {
return {
species: this.species,
weight: this.weight,
diet: this.diet,
enclosureId: this.enclosureId,
energy: this.energy,
status: this.isActive ? 'Active' : 'Sleeping'
};
}
makeSound() {
if (!this.isActive) {
return `${this.species} is sleeping... zzz`;
}
const sounds = {
'carnivore': 'ROAAAAR!',
'herbivore': 'Moooo!',
'omnivore': 'Grrrrr!'
};
return `${this.species}: ${sounds[this.diet] || 'Hmm?'}`;
}
feed() {
if (!this.isActive) {
return `${this.species} is sleeping and cannot be fed`;
}
this.energy = Math.min(100, this.energy + 20);
this.lastFed = new Date();
return `Fed ${this.species}. Energy: ${this.energy}%`;
}
sleep() {
this.isActive = false;
this.energy = Math.min(100, this.energy + 10);
return `${this.species} goes to sleep. Energy: ${this.energy}%`;
}
wakeUp() {
this.isActive = true;
return `${this.species} is waking up!`;
}
exercise() {
if (!this.isActive) {
return `${this.species} is sleeping and cannot exercise`;
}
this.energy = Math.max(0, this.energy - 15);
if (this.energy < 20) {
return `${this.species} is tired and needs rest. Energy: ${this.energy}%`;
}
return `${this.species} is exercising! Energy: ${this.energy}%`;
}
// Getter and setter
get status() {
if (!this.isActive) return 'sleeping';
if (this.energy > 80) return 'full of energy';
if (this.energy > 50) return 'active';
if (this.energy > 20) return 'tired';
return 'exhausted';
}
set energyLevel(value) {
this.energy = Math.max(0, Math.min(100, value));
}
}
// Creating dinosaurs with constructor
const triceratops = new DinosaurAdvanced('Triceratops', 6000, 'herbivore', 'ENC-002');
const velociraptor = new DinosaurAdvanced('Velociraptor', 15, 'carnivore', 'ENC-003');
console.log("Triceratops info:", triceratops.getInfo());
console.log("Velociraptor sound:", velociraptor.makeSound());
// Testing methods
console.log(triceratops.feed());
console.log(triceratops.exercise());
console.log("Status Triceratops:", triceratops.status);
// ===========================================
// 3. Static methods
// ===========================================
console.log("\n=== 3. Static methods ===");
class DinosaurManager {
static totalDinosaurs = 0;
static enclosures = new Map();
constructor(species, weight, diet, enclosureId) {
this.species = species;
this.weight = weight;
this.diet = diet;
this.enclosureId = enclosureId;
this.id = DinosaurManager.generateId();
this.isActive = true;
// Increase counter
DinosaurManager.totalDinosaurs++;
// Add to paddock
DinosaurManager.addToEnclosure(this);
}
// Static method - ID generation
static generateId() {
return 'DINO-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
}
// Static method - comparing dinosaurs
static compare(dino1, dino2) {
if (dino1.weight > dino2.weight) {
return `${dino1.species} is heavier than ${dino2.species}`;
} else if (dino1.weight < dino2.weight) {
return `${dino2.species} is heavier than ${dino1.species}`;
} else {
return `${dino1.species} and ${dino2.species} have similar weight`;
}
}
// Static method - statistics
static getStatistics() {
const byDiet = {};
const byEnclosure = {};
for (const [enclosureId, dinosaurs] of DinosaurManager.enclosures) {
byEnclosure[enclosureId] = dinosaurs.length;
dinosaurs.forEach(dino => {
byDiet[dino.diet] = (byDiet[dino.diet] || 0) + 1;
});
}
return {
total: DinosaurManager.totalDinosaurs,
byDiet,
byEnclosure
};
}
// Static method - paddock management
static addToEnclosure(dinosaur) {
if (!DinosaurManager.enclosures.has(dinosaur.enclosureId)) {
DinosaurManager.enclosures.set(dinosaur.enclosureId, []);
}
DinosaurManager.enclosures.get(dinosaur.enclosureId).push(dinosaur);
}
// Static method - find dinosaurs in paddock
static getDinosaursInEnclosure(enclosureId) {
return DinosaurManager.enclosures.get(enclosureId) || [];
}
getInfo() {
return `${this.species} (ID: ${this.id}) - ${this.weight}kg`;
}
}
// Testing static methods
const stegosaurus = new DinosaurManager('Stegosaurus', 5000, 'herbivore', 'ENC-002');
const allosaurus = new DinosaurManager('Allosaurus', 4000, 'carnivore', 'ENC-004');
const brachiosaurus = new DinosaurManager('Brachiosaurus', 80000, 'herbivore', 'ENC-005');
console.log("Generated ID:", DinosaurManager.generateId());
console.log("Comparison:", DinosaurManager.compare(stegosaurus, allosaurus));
console.log("Park statistics:", DinosaurManager.getStatistics());
console.log("Dinosaurs in ENC-002:", DinosaurManager.getDinosaursInEnclosure('ENC-002').map(d => d.species));
// ===========================================
// 4. Inheritance and derived classes
// ===========================================
console.log("\n=== 4. Class inheritance ===");
// Base class
class Animal {
constructor(species, weight) {
this.species = species;
this.weight = weight;
this.isAlive = true;
}
breathe() {
return `${this.species} is breathing`;
}
move() {
return `${this.species} is moving`;
}
}
// Inheriting class
class CarnivorousDinosaur extends Animal {
constructor(species, weight, huntingStyle, packSize = 1) {
super(species, weight); // Calling base class constructor
this.diet = 'carnivore';
this.huntingStyle = huntingStyle;
this.packSize = packSize;
this.lastHunt = null;
}
// Method override from the base class
move() {
return `${this.species} is sneaking quietly...`;
}
// New methods specific to carnivores
hunt(prey) {
this.lastHunt = new Date();
if (this.packSize > 1) {
return `Herd of ${this.species} (${this.packSize} individuals) hunts ${prey} using strategy: ${this.huntingStyle}`;
} else {
return `${this.species} hunts ${prey} using strategy: ${this.huntingStyle}`;
}
}
roar() {
const intensity = this.weight > 1000 ? 'POWERFUL' : 'loud';
return `${this.species} lets out a ${intensity} roar: ROAAAAR!`;
}
}
// Second inheriting class
class HerbivorousDinosaur extends Animal {
constructor(species, weight, defenseType, herdSize = 1) {
super(species, weight);
this.diet = 'herbivore';
this.defenseType = defenseType;
this.herdSize = herdSize;
this.foodConsumed = 0;
}
move() {
if (this.herdSize > 1) {
return `Herd of ${this.species} (${this.herdSize} individuals) migrates in search of food`;
}
return `${this.species} walks calmly through the forest`;
}
graze() {
const amount = Math.floor(this.weight * 0.1); // 10% of weight daily
this.foodConsumed += amount;
return `${this.species} eats plants. Today consumed: ${this.foodConsumed}kg`;
}
defend() {
return `${this.species} uses defense type: ${this.defenseType}!`;
}
makeNoise() {
return `${this.species} makes a calm herd communication sound`;
}
}
// Creating instances of inheriting classes
const tyrannosaurs = new CarnivorousDinosaur('Tyrannosaurus Rex', 8000, 'lone hunter');
const velociraptors = new CarnivorousDinosaur('Velociraptor', 15, 'coordinated pack attack', 6);
const triceratopsHerd = new HerbivorousDinosaur('Triceratops', 6000, 'sharp horns', 12);
const stegosaurusGroup = new HerbivorousDinosaur('Stegosaurus', 5000, 'tail spikes', 8);
console.log("\nCarnivores:");
console.log(tyrannosaurs.move());
console.log(tyrannosaurs.hunt('Triceratops'));
console.log(tyrannosaurs.roar());
console.log(velociraptors.move());
console.log(velociraptors.hunt('Hadrosaurus'));
console.log("\nHerbivores:");
console.log(triceratopsHerd.move());
console.log(triceratopsHerd.graze());
console.log(triceratopsHerd.defend());
console.log(stegosaurusGroup.graze());
console.log(stegosaurusGroup.makeNoise());
// ===========================================
// 5. Private properties and methods (ES2022)
// ===========================================
console.log("\n=== 5. Private fields and methods ===");
class SecureDinosaur {
// Public properties
species;
weight;
// Private properties (ES2022)
#dna;
#securityLevel;
#lastHealthCheck;
constructor(species, weight, dna, securityLevel) {
this.species = species;
this.weight = weight;
this.#dna = dna;
this.#securityLevel = securityLevel;
this.#lastHealthCheck = new Date();
}
// Private method
#validateSecurity(requestedLevel) {
return requestedLevel <= this.#securityLevel;
}
#analyzeDNA() {
return `DNA analysis: ${this.#dna.substring(0, 10)}...`;
}
// Public methods
getBasicInfo() {
return {
species: this.species,
weight: this.weight,
securityLevel: this.#securityLevel
};
}
getSecureInfo(securityClearance) {
if (!this.#validateSecurity(securityClearance)) {
return "Access denied - insufficient security level";
}
return {
species: this.species,
weight: this.weight,
dnaAnalysis: this.#analyzeDNA(),
lastHealthCheck: this.#lastHealthCheck.toLocaleDateString(),
securityLevel: this.#securityLevel
};
}
performHealthCheck(doctorClearance) {
if (!this.#validateSecurity(doctorClearance)) {
return "Unauthorized access to health research";
}
this.#lastHealthCheck = new Date();
return `Health examination ${this.species} completed successfully`;
}
}
// Testing private fields
const secureTRex = new SecureDinosaur(
'Tyrannosaurus Rex',
8000,
'ATCGATCGATCGATCG...',
5
);
console.log("Basic info:", secureTRex.getBasicInfo());
console.log("Access attempt with clearance 3:", secureTRex.getSecureInfo(3));
console.log("Access with clearance 5:", secureTRex.getSecureInfo(5));
console.log("Health examination:", secureTRex.performHealthCheck(5));
// Attempt directly accessing private fields (will return undefined)
console.log("Attempt to access #dna:", secureTRex.dna); // undefined, and secureTRex.#dna outside the class is a SyntaxError
// ===========================================
// 6. Getters and setters
// ===========================================
console.log("\n=== 6. Getters and setters ===");
class SmartDinosaur {
constructor(species, weight, age) {
this._species = species;
this._weight = weight;
this._age = age;
this._healthStatus = 'healthy';
}
// Getter
get species() {
return this._species.toUpperCase();
}
get weight() {
return this._weight;
}
// Setter with validation
set weight(value) {
if (typeof value !== 'number' || value <= 0) {
throw new Error('Weight must be a positive number');
}
const oldWeight = this._weight;
this._weight = value;
console.log(`Weight of ${this._species} changed from ${oldWeight}kg to ${value}kg`);
}
get age() {
return this._age;
}
set age(value) {
if (typeof value !== 'number' || value < 0) {
throw new Error('Age cannot be negative');
}
this._age = value;
this.#updateHealthStatus();
}
// Computed getter
get bmi() {
// Simplified BMI for dinosaurs (weight / length²)
const estimatedLength = Math.sqrt(this._weight / 100); // Approximate length
return (this._weight / (estimatedLength * estimatedLength)).toFixed(2);
}
get status() {
const ageCategory = this._age < 5 ? 'young' : this._age < 20 ? 'adult' : 'old';
return `${this._species}: ${ageCategory}, ${this._healthStatus}, BMI: ${this.bmi}`;
}
// Private helper method
#updateHealthStatus() {
if (this._age > 25) {
this._healthStatus = 'advanced age';
} else if (this._age > 15) {
this._healthStatus = 'mature';
} else {
this._healthStatus = 'healthy';
}
}
}
const smartRaptor = new SmartDinosaur('Velociraptor', 25, 8);
console.log("Species (getter):", smartRaptor.species);
console.log("Status:", smartRaptor.status);
// Using setter
smartRaptor.weight = 30;
smartRaptor.age = 18;
console.log("New status:", smartRaptor.status);
// Testing setter validation
try {
smartRaptor.weight = -5; // To will cause an error
} catch (error) {
console.log("Error:", error.message);
}
console.log("\nCongratulations! You've mastered ES6 classes in Jurassic Park!");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. How do you correctly define a class in JavaScript ES6?