DEV Community

Cover image for A Comprehensive Guide to JavaScript Classes
Anton Martyniuk
Anton Martyniuk

Posted on • Originally published at antondevtips.com on

A Comprehensive Guide to JavaScript Classes

Read original blog post on my website https://antondevtips.com.

Today you will learn about Object-Oriented Programing in JavaScript.
You will learn how to create JavaScript classes, use constructors, define fields and methods, use static members, and implement inheritance.

In JavaScript in ES6 classes were introduced as a new and better mechanism for creating objects.
Previously, JavaScript used prototype-based inheritance.

How to Create a Class in JavaScript

To create a class in JavaScript, you need to use a class keyword:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

Class may contain the following parts:

  • constructors
  • fields: public and private
  • methods
  • getters, setters
  • static members

Constructors in JavaScript Classes

The constructor is a special method called when a new instance of the class is created.
It's typically used to initialize clas properties.

const person = new Person("Anton", 30);
console.log(person.name); // Output: Anton
console.log(person.age); // Output: 30
Enter fullscreen mode Exit fullscreen mode

Fields in JavaScript Classes

Fields in JavaScript classes can be public or private.
Public fields are accessible from outside of the class, while private fields are not.

Here is how to declare public fields.

class Person {
  name;
  age;

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice that fields don't have their types specified.

To declare a private field, put # sign before the field name:

class Person {
  name;
  age;
  #phone;

  constructor(name, age, phone) {
    this.name = name;
    this.age = age;
    this.phone = phone;
  }
}

const person = new Person("Anton", 30, "123456789");
console.log(person.name); // Output: Anton
console.log(person.age); // Output: 30

// Error accessing private class member
//console.log(person.#phone);
Enter fullscreen mode Exit fullscreen mode

If you try to access a private field, you'll get an error.

Methods in JavaScript Classes

Methods are functions defined within a class.
They provide behavior to class instances and can manipulate instance fields or perform operations related to the class.

Classes can have methods that return a value or receive arguments:

class Rectangle {
  width;
  height;

  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  getSquare() {
    return this.width * this.height;
  }
}

const rect = new Rectangle(5, 10);
console.log(rect.getSquare()); // Output: 50
Enter fullscreen mode Exit fullscreen mode
class Logger {
  print(text) {
    console.log(text);
  }
}

const logger = new Logger();
logger.print("Hello JavaScript");
Enter fullscreen mode Exit fullscreen mode

Static Members in JavaScript Classes

Static members belong to the class itself.
They are shared among all instances of the class and can be accessed using the class name.
Static fields are defined using the static keyword.

Classes can have static fields and methods.
Static fields are defined using the static keyword:

class Car {
  static totalCars = 0;

  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
    Car.totalCars++;
  }
}

const car1 = new Car("Toyota", "Camry");
const car2 = new Car("Honda", "Accord");

console.log(Car.totalCars); // Output: 2
console.log(car1.totalCars); // Output: undefined
console.log(car2.totalCars); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

In this example, totalCars is a static field of the Car class.
It keeps track of the total number of Car instances created.
Each time a new Car is instantiated, the totalCars field is incremented.
The totalCars field can be accessed only by using the class name (Car.totalCars), not through the instances (car1 or car2).

Static methods are functions that belong to the class itself.
They can perform operations that are related to the class but do not require an instance to be created.
Static methods are also defined using the static keyword:

class Calculator {
  static add(a, b) {
    return a + b;
  }
}

const result = Calculator.add(5, 10);
console.log(result); // Output: 15
Enter fullscreen mode Exit fullscreen mode

In this example, add is a static methods of the Calculator class.
This method can be called directly on the class without creating an instance of Calculator.
Static methods are typically used for utility functions that are a part of the class instance.

Combining Static Fields and Static Methods

Static fields and static methods can be combined in classes.
Static methods are related to the class, that's why they can access only static fields:

class Circle {
  static PI = 3.14159;

  static calculateArea(radius) {
    return Circle.PI * radius * radius;
  }
}

const radius = 5;
const area = Circle.calculateArea(radius);

// Output: Area of circle with radius 5 = 78.53975
console.log(`Area of circle with radius ${radius} = ${area}`);
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance allows one class (child class) to inherit properties and methods from another class (parent class).
This helps in reusing code and creating a more organized class hierarchy.

Parent class is also called - superclass and the child - the subclass.

Let's have a look at Car and ElectricCar classes.
ElectricCar class can inherit properties and methods from the Car class to avoid duplication.

First, let's define the base Car class:

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  start() {
    console.log(`${this.brand} ${this.model} has started.`);
  }

  drive() {
    console.log(`${this.brand} ${this.model} is driving.`);
  }

  stop() {
    console.log(`${this.brand} ${this.model} has stopped.`);
  }
}

const car = new Car("Ford", "Mustang");
car.start();
car.drive();
car.stop();
Enter fullscreen mode Exit fullscreen mode

Now, let's extend the Car class to create an ElectricCar class.
The ElectricCar class will inherit properties and methods from the Car class and add some additional properties and methods specific to electric cars:

class ElectricCar extends Car {
  constructor(brand, model, batteryCapacity) {
    super(brand, model);
    this.batteryCapacity = batteryCapacity;
  }

  start() {
    console.log(`${this.brand} ${this.model} has started silently.`);
  }

  drive() {
    console.log(`${this.brand} ${this.model} is driving.`);
  }

  stop() {
    console.log(`${this.brand} ${this.model} has stopped.`);
  }

  charge() {
    console.log(`${this.brand} ${this.model} is charging with ${this.batteryCapacity} kWh battery.`);
  }
}

const tesla = new ElectricCar("Tesla", "Model S", 100);
car.charge();
car.start();
car.drive();
car.stop();
Enter fullscreen mode Exit fullscreen mode

Let's explain both classes in details.

  1. The ElectricCar class extends the Car class using the extends keyword.
    This makes the ElectricCar class as a subclass of Car.

  2. The constructor of ElectricCar calls the parent class's constructor using the super keyword, passing brand and model to it.
    This is needed to initialize properties of the parent class.
    The batteryCapacity is a new property specific to the ElectricCar class.

  3. The ElectricCar class overrides the start method of the Car class.
    When start is called on an ElectricCar instance, it uses the overridden method that logs a different message.

  4. The ElectricCar class defines a new method charge, which is specific to electric cars and not present in the Car class.

Hope you find this blog post useful. Happy coding!

Read original blog post on my website https://antondevtips.com.

After reading the post consider the following:

  • Subscribe to receive newsletters with the latest blog posts
  • Download the source code for this post from my github (available for my sponsors on BuyMeACoffee and Patreon)

If you like my content —  consider supporting me

Unlock exclusive access to the source code from the blog posts by joining my Patreon and Buy Me A Coffee communities!

Top comments (0)