Object-Oriented JavaScript: Structuring Complex Logic
9 min read
🧱 Object-Oriented JavaScript: Structuring Complex Logic
Welcome! As our applications grow, so does our logic. Simply writing functions one after another can get messy, like throwing all your clothes in one giant pile. Object-Oriented Programming (OOP) is a way to organize this complexity by bundling related data and behavior into neat packages called "objects."
Imagine building a complex system, like a car factory. You wouldn't manage every single screw and bolt individually. Instead, you'd have blueprints for an "Engine," a "Chassis," and a "Transmission." Each of these components has its own internal parts (data) and can perform specific actions (behavior). OOP lets us create these kinds of "blueprints" in our code.
Let's dive into the core concepts that make this possible in JavaScript.
1. The 'this' Keyword: Understanding Execution Context
The Problem 🤔
Imagine you have two separate remote controls for two different TVs. Each remote has a power button. When you press power on one remote, how does it know to turn on its specific TV and not the other one? It has a sense of its own context.
In JavaScript, objects have methods (functions inside an object). How does a method know which object it's supposed to be working on?
let user1 = {
name: "Alice",
sayHi: function() {
console.log("Hi, I am " + ???); // How do we get "Alice" here?
}
};
let user2 = {
name: "Bob",
sayHi: function() {
console.log("Hi, I am " + ???); // And how do we get "Bob" here?
}
};This is the problem the this keyword solves.
What is 'this'?
The this keyword refers to the object that is currently executing the code. Its value is determined by how a function is called, not where it is defined. This is a crucial point that trips up many developers.
The 'this' Keyword in Action 🎬
Let's solve our problem from before. When a function is called as a method of an object, this refers to that object.
let user = {
name: "Alice",
age: 25,
introduce: function() {
// 'this' here refers to the 'user' object
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
user.introduce(); // Output: Hello, my name is Alice and I am 25 years old.Here, user.introduce() tells JavaScript to run the introduce function in the context of the user object. Therefore, this.name becomes user.name.
An Interesting Quirk: If you call the same function without an object context, this can change! In non-strict mode, it defaults to the global object (window in browsers).
const standAloneIntroduce = user.introduce;
standAloneIntroduce(); // "Hello, my name is undefined and I am undefined years old."This happens because standAloneIntroduce isn't being called on the user object anymore. It has lost its context.
Industry Practice: The behavior of
thiscan be confusing. With the introduction of ES6 Classes, managingthishas become much more straightforward, as it's automatically set up correctly in most cases within a class. Arrow functions also handlethisdifferently; they inherit it from their parent's scope, which can be very useful but is a topic for another day!
2. ES6 Classes: Blueprints for Objects
The Problem 🤔
Let's say we're building a social media app. We need to create profiles for thousands of users. Each user will have a username and a followerCount, and they should be able to postUpdate.
We could create each user object manually:
const userOne = {
username: "DevGuru",
followerCount: 1024,
postUpdate: function() { /* ... logic ... */ }
};
const userTwo = {
username: "CodeWizard",
followerCount: 2048,
postUpdate: function() { /* ... logic ... */ }
};This is repetitive and highly error-prone. If we need to fix a bug in postUpdate, we have to change it in every single user object! There must be a better way.
What is a Class? ⚙️
A class is a blueprint for creating objects. It defines a template with properties (data) and methods (behavior) that all objects created from that class will share. Introduced in ES6, classes are primarily "syntactic sugar" over JavaScript's existing prototype-based inheritance, making the syntax cleaner and more familiar to developers coming from other languages like Java or C++.
Think of it like a cookie cutter. The class is the cutter, and the objects are the cookies. They all have the same shape, but you can give each one unique decorations.
Creating Your First Class
Here’s how we can create a User blueprint. By convention, class names start with a capital letter.
class User {
// The constructor is a special method for creating and initializing an object.
constructor(username, initialFollowers) {
this.username = username;
this.followerCount = initialFollowers;
}
// This is a method. All users will be able to call it.
postUpdate(message) {
console.log(`${this.username} posted: "${message}"`);
}
}
// Now, let's use our blueprint to create 'instances' of the User class.
const userOne = new User("DevGuru", 1024);
const userTwo = new User("CodeWizard", 2048);
userOne.postUpdate("I'm learning about classes!");
// Output: DevGuru posted: "I'm learning about classes!"
console.log(userTwo.username); // Output: CodeWizardThis is much cleaner! We define the structure once and can create as many consistent objects (called "instances") as we need using the new keyword.
Fun Fact: Before ES6 classes, developers used "constructor functions" to achieve a similar result. Classes provide a much more readable and less error-prone syntax for the same underlying mechanism.
3. Constructors and Class Methods
We've already seen them in action, but let's break them down.
The Constructor Method 🛠️
The Problem: We have a User blueprint, but how do we give each user their unique username and starting follower count when they're created?
The Solution: The constructor method.
A constructor is a special method inside a class that gets executed automatically when you create a new instance of that class (i.e., when you use the new keyword). Its primary job is to set up the initial properties of the object.
- A class can only have one method with the name
constructor. - It's the perfect place to assign values to properties using the
thiskeyword.thisinside the constructor refers to the new object instance being created.
class Car {
// This constructor runs when we do 'new Car(...)'
constructor(make, model, year) {
console.log("A new car is rolling off the assembly line!");
this.make = make; // 'this' refers to the new car object
this.model = model;
this.year = year;
this.speed = 0;
}
}
const myCar = new Car("Honda", "Civic", 2024);
// Output: A new car is rolling off the assembly line!
console.log(myCar.make); // Output: HondaClass Methods 🏎️
The Problem: Our Car object has data (make, model, speed), but it can't do anything. How do we make it accelerate or brake?
The Solution: Class methods.
Methods are simply functions defined within a class. They define the behavior and actions that an object created from the class can perform.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
this.speed = 0;
}
// Method to increase speed
accelerate(amount) {
this.speed += amount;
console.log(`The ${this.make} ${this.model} is now going ${this.speed} mph.`);
}
// Method to decrease speed
brake(amount) {
this.speed -= amount;
if (this.speed < 0) {
this.speed = 0;
}
console.log(`The ${this.make} ${this.model} slowed down to ${this.speed} mph.`);
}
}
const myCar = new Car("Tesla", "Model 3");
myCar.accelerate(50); // Output: The Tesla Model 3 is now going 50 mph.
myCar.accelerate(20); // Output: The Tesla Model 3 is now going 70 mph.
myCar.brake(30); // Output: The Tesla Model 3 slowed down to 40 mph.All instances of Car will share the accelerate and brake methods, but they will operate on each instance's unique speed property.
4. Inheritance: Extending Classes to Share Behavior
The Problem 🤔
We have our Car class. Now, our factory wants to build ElectricCars. An electric car is still a car—it has a make, model, and speed. But it also has a batteryRange.
We could copy-paste the entire Car class and just add the new property:
class ElectricCar {
constructor(make, model, batteryRange) {
this.make = make;
this.model = model;
this.speed = 0;
this.batteryRange = batteryRange; // The new property
}
accelerate(amount) { /* ... same code as Car ... */ }
brake(amount) { /* ... same code as Car ... */ }
charge() {
console.log("Charging...");
}
}This is a terrible idea! We're duplicating code. If we find a bug in accelerate, we have to fix it in both Car and ElectricCar.
What is Inheritance? 👨👩👧👦
Inheritance allows a new class (the "child" or "subclass") to acquire the properties and methods of an existing class (the "parent" or "superclass"). We use the extends keyword to establish this relationship. The child class can then add its own new properties and methods or even change (override) the ones it inherited.
Think of it this way: A Square is a Rectangle but with its own special rules (all sides are equal). A Dog is an Animal, but it can also bark.
Using extends and super
Let's refactor our ElectricCar to inherit from Car.
extends: This keyword tells JavaScript thatElectricCaris a child ofCar.super(): Inside the child class's constructor, you must callsuper()before you can use thethiskeyword. Thesuper()call executes the parent class's constructor, which handles the setup for the inherited properties (make,model, etc.).
// Parent Class (Superclass)
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
this.speed = 0;
}
accelerate(amount) {
this.speed += amount;
console.log(`The ${this.make} ${this.model} is now going ${this.speed} mph.`);
}
brake(amount) {
this.speed -= amount;
console.log(`Slowing down to ${this.speed} mph.`);
}
}
// Child Class (Subclass)
class ElectricCar extends Car {
constructor(make, model, batteryRange) {
// 1. Call the parent constructor to set up make and model
super(make, model);
// 2. Now set up the properties specific to ElectricCar
this.batteryRange = batteryRange;
}
// New method only for ElectricCar
checkRange() {
console.log(`Remaining range: ${this.batteryRange} miles.`);
}
}
const myEV = new ElectricCar("Rivian", "R1T", 300);
myEV.accelerate(60); // Inherited from Car -> Output: The Rivian R1T is now going 60 mph.
myEV.checkRange(); // Belongs to ElectricCar -> Output: Remaining range: 300 miles.Look at that! No code duplication. We get all the functionality of Car for free and can cleanly add what makes an ElectricCar unique. This makes our code much more maintainable and scalable.
📚 Further Reading and References
- MDN Documentation on Classes: MDN Classes
- Understanding
this: MDN 'this' keyword - Inheritance (
extends): MDN extends keyword - The
superkeyword: MDN super keyword
Challenge
Your task is to implement a class hierarchy for vehicles using ES6 classes, demonstrating your understanding of constructors, methods, inheritance, and method overriding.
Requirements:
1. Vehicle Base Class:
- Create a class named
Vehicle. - The
constructorshould acceptmake,model, andyearas arguments and assign them to the instance. - Initialize a property
speedto0within the constructor. - Implement a method
accelerate(amount)that increases thespeedproperty by the givenamount. - Implement a method
brake(amount)that decreases thespeedproperty by the givenamount. The speed should not be allowed to go below0. - Implement a method
getDetails()that returns a string in the format:"Make: [make], Model: [model], Year: [year]".
2. Motorcycle Child Class:
- Create a class named
Motorcyclethat inherits fromVehicle. - The
constructorshould acceptmake,model,year, andnumWheels. - It must properly initialize the inherited properties from the
Vehicleclass using the parent constructor. - It should also initialize its own
numWheelsproperty. - Implement a specific method
wheelie()that returns the string"Performing a wheelie!"if the motorcycle's currentspeedis greater than50, otherwise it should return"Too slow for a wheelie.". - Override the
getDetails()method to include the number of wheels. The returned string should be in the format:"Make: [make], Model: [model], Year: [year], Wheels: [numWheels]".
Expected result
The final code should contain two class definitions: Vehicle and Motorcycle.
- The
Vehicleclass must have aconstructorthat initializesmake,model,year, andspeed. - The
Vehicleclass must include the methodsaccelerate,brake, andgetDetails, with thebrakemethod containing logic to prevent the speed from becoming negative. - The
Motorcycleclass definition must use theextends Vehiclesyntax. - The
Motorcycleconstructor must callsuper(make, model, year)to delegate initialization to the parent class, and then set its ownnumWheelsproperty. - The
Motorcycleclass must contain thewheeliemethod with the correct conditional logic based on thespeedproperty. - The
Motorcycleclass must also contain its owngetDetailsmethod, overriding the parent's method to provide the extended details string.