Learn JavaScript · 13/15

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?

javascript
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.

javascript
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).

javascript
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 this can be confusing. With the introduction of ES6 Classes, managing this has become much more straightforward, as it's automatically set up correctly in most cases within a class. Arrow functions also handle this differently; 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:

javascript
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.

javascript
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: CodeWizard

This 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 this keyword. this inside the constructor refers to the new object instance being created.
javascript
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: Honda

Class 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.

javascript
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:

javascript
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.

  1. extends: This keyword tells JavaScript that ElectricCar is a child of Car.
  2. super(): Inside the child class's constructor, you must call super() before you can use the this keyword. The super() call executes the parent class's constructor, which handles the setup for the inherited properties (make, model, etc.).
javascript
// 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

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 constructor should accept make, model, and year as arguments and assign them to the instance.
  • Initialize a property speed to 0 within the constructor.
  • Implement a method accelerate(amount) that increases the speed property by the given amount.
  • Implement a method brake(amount) that decreases the speed property by the given amount. The speed should not be allowed to go below 0.
  • 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 Motorcycle that inherits from Vehicle.
  • The constructor should accept make, model, year, and numWheels.
  • It must properly initialize the inherited properties from the Vehicle class using the parent constructor.
  • It should also initialize its own numWheels property.
  • Implement a specific method wheelie() that returns the string "Performing a wheelie!" if the motorcycle's current speed is greater than 50, 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.

  1. The Vehicle class must have a constructor that initializes make, model, year, and speed.
  2. The Vehicle class must include the methods accelerate, brake, and getDetails, with the brake method containing logic to prevent the speed from becoming negative.
  3. The Motorcycle class definition must use the extends Vehicle syntax.
  4. The Motorcycle constructor must call super(make, model, year) to delegate initialization to the parent class, and then set its own numWheels property.
  5. The Motorcycle class must contain the wheelie method with the correct conditional logic based on the speed property.
  6. The Motorcycle class must also contain its own getDetails method, overriding the parent's method to provide the extended details string.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.