Classes, Inheritance & Constructors in JS

Master the blueprints of JavaScript to build organized, reusable, and powerful applications with Object-Oriented principles.

📝

Welcome! Let's explore how to create object blueprints in JavaScript using classes.

/* Blueprints for Objects */

The 'class' as a Blueprint

A class in JavaScript is a blueprint for creating objects. It encapsulates data (properties) and functions (methods) that operate on that data. Think of it as a cookie cutter: you define the shape once, then you can create many cookies (objects) from it.

The `constructor` Method

The `constructor` is a special method inside a class for creating and initializing an object. It's automatically called when you create a new instance of the class using the `new` keyword. Its job is to set up the initial properties of the object.

Inheritance with `extends` & `super`

Inheritance allows a new class (child) to inherit properties and methods from an existing class (parent). This is achieved with the `extends` keyword. To call the parent's constructor from the child, you must use the `super()` method.

Creating Instances with `new`

An instance is a concrete object created from a class. You create an instance using the `new` keyword followed by the class name. Each instance is a separate object with its own properties, but shares the methods defined in the class blueprint.

Practice Zone


Interactive Test 1: Match the Concepts

Drag the keywords to their correct descriptions.

Arrastra en el orden correspondiente.


Arrastra las opciones:

new
super()
extends
class

Completa el código:

Blueprint for objects______
Used for inheritance______
Calls the parent constructor______
Creates an instance______
Unlock with Premium

Interactive Test 2: Build the Inheritance

Complete the code to define a `Dog` class that inherits from `Animal`.

Rellena los huecos en cada casilla.

class Animal { /* ... */ }

class Dog  Animal {
  (name, breed) {
    (name);
    this.breed = breed;
  }
}
Unlock with Premium

Practice Example: Code Your First Class

Create a `Car` class with a `constructor` for `brand` and `year`. Then, create an instance of the car.

Enunciado:

* Escribe el código a continuación. Los caracteres correctos se mostrarán en verde y los incorrectos en rojo.

class Car { constructor(brand, year) { this.brand = brand; this.year = year; } } const myCar = new Car("Toyota", 2024);
Unlock with Premium

Knowledge Check

What is the primary purpose of the 'super()' keyword in a child class constructor?


Unlock with Premium

Classes in the Real World

Classes are not just theoretical; they are the backbone of many complex applications. Here’s how they are practically used.


1. Building UI Components

In frameworks like React (using class components), each part of your UI—a button, a form, a profile card—can be a class. It holds its own state (data) and methods (logic), making your code organized and reusable.

// A simplified React class component
class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }

  render() { /* ...JSX to render button */ }
}

2. Managing Game Characters

In game development, you might have a base `Character` class. Then, `Player` and `Enemy` classes can inherit from it, sharing common methods like `move()` while having their own unique abilities.

class Character {
  attack() { console.log('Basic attack!'); }
}

class Player extends Character {
  specialMove() { console.log('Fireball!'); }
}

3. Structuring Application Data

When fetching data from an API, you can structure it into classes. A `User` class could have methods like `getFullName()` or `hasPermission()`, making the data much easier and more predictable to work with.

class User {
  constructor(apiData) { /* ... */ }

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

Practical Takeaway: Classes help you model real-world concepts in your code, leading to applications that are more organized, scalable, and easier to maintain.

JavaScript OOP Glossary

class
A keyword that defines a template or blueprint for creating objects.
constructor
A special method within a class that initializes a new object instance.
extends
A keyword used to create a child class that inherits from a parent class.
super
A keyword used to call methods on a parent class, most commonly the parent's constructor.
new
An operator that creates a new instance of a class.
this
A keyword that refers to the current object instance within a class method or constructor.
instance
A concrete object created from a class.
method
A function defined within a class that can be called on instances of that class.
property
A variable associated with a class instance that holds a value.