JAVASCRIPT

JavaScript Class: Creating Classes and Objects in JS

In JavaScript, a class is a blueprint for creating objects with predefined properties and methods. JavaScript classes provide a convenient way to create constructor functions and handle inheritance.

How to Use JavaScript Classes

Creating JavaScript Classes

A JavaScript class declaration consists of the class keyword followed by the class name. Within the curly braces of the class body, you can add class methods, including the class constructor method.

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
  • class: The keyword to create a class in JavaScript.
  • constructor: A special method for creating objects from the class.

Creating Instances of JavaScript Classes

To create a new object from a class, you need the new keyword. Essentially, new creates an object of the class by allocating memory for it and calling the constructor method:

let myCar = new Car("VW");
  • new: The keyword to create an instance of a class, which triggers the class constructor.

When to Use JavaScript Classes

Classes in JavaScript are a fundamental component of object-oriented programming. A class is useful for creating multiple instances of a type of object with similar functionalities, encapsulation, and inheritance.

Creating Similar Objects

You can use a class to represent objects with similar functionalities or properties.

let square = new Rectangle(5, 5);
let poster = new Rectangle(2, 3);

Encapsulation

Also, classes help you encapsulate data. Encapsulation bundles data and methods that change or otherwise use data within a class. In doing so, it limits direct access to some of the object's components to prevent accidental changes.

Here's an example of encapsulation using a BankAccount class:

class BankAccount {
  #accountBalance; // Private field

  constructor(initialBalance) {
    this.#accountBalance = initialBalance;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#accountBalance += amount;
      console.log(`Deposit of $${amount} successful. Balance is now $${this.#accountBalance}.`);
    } else {
      console.log("Invalid deposit amount.");
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.#accountBalance) {
      this.#accountBalance -= amount;
      console.log(`Withdrawal of $${amount} successful. Balance is now $${this.#accountBalance}.`);
    } else {
      console.log("Insufficient funds or invalid amount.");
    }
  }

  get balance() {
    return this.#accountBalance;
  }
}

let myAccount = new BankAccount(1000);
myAccount.deposit(500);  // Deposit $500
myAccount.withdraw(200); // Withdraw $200
console.log(`Current balance: $${myAccount.balance}`); // Access balance using getter

Inheritance

Classes are beneficial for inheritance, where one class inherits the properties and methods of another.

class Square extends Rectangle {
  constructor(side) {
    super(side, side);
  }
}

Examples of JavaScript Classes

JavaScript classes are ubiquitous in web and software development. Here are some simplified examples of classes:

User Accounts

Classes can manage user properties and methods, such as creating a new user account or updating user information.

class User {
  constructor(username, email) {
    this.username = username;
    this.email = email;
  }
  updateEmail(newEmail) {
    this.email = newEmail;
  }
}
let user1 = new User("johnDoe", "john@example.com");

Game Characters

In game development, classes can define properties and actions of characters, enhancing reusability and scalability.

class Character {
  constructor(name, strength) {
    this.name = name;
    this.strength = strength;
  }
  attack() {
    console.log(`${this.name} attacks with strength ${this.strength}`);
  }
}
let hero = new Character("Warrior", 75);

Learn More About JavaScript Classes

Static Methods

Static methods are methods that belong to a class itself, not to the instances of the class. Classes often use static methods to create utility functions for an application. To create static method, use the static keyword at the beginning of the function's declaration.

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return Math.hypot(dx, dy);
  }
}

Static Properties

Static properties store class-level data, as opposed to the instance-level data of object properties. A static property can be useful for caches and configurations. To create a static property, add static in front of a property’s declaration.

class Battery {
  static voltage = 12;  // Static property

  constructor(capacity) {
    this.capacity = capacity;
  }
}

console.log(Battery.voltage);  // Accessing the static property

Getter and Setter Methods

Getter and setter methods allow you to define methods in a class that look and behave like properties. Getters and setters allow you to get and set the values of properties with additional checks or control mechanisms. To create a getter or setter method, use the get or set keyword with the property name like in a function declaration.

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  // Getter to convert celsius to fahrenheit
  get fahrenheit() {
    return this.celsius * 1.8 + 32;
  }

  // Setter to set the temperature in celsius based on fahrenheit input
  set fahrenheit(value) {
    this.celsius = (value - 32) / 1.8;
  }
}

let temp = new Temperature(25); // Setting temperature in Celsius
console.log(`${temp.celsius}°C is equivalent to ${temp.fahrenheit}°F.`); // Using getter to show Fahrenheit

temp.fahrenheit = 86; // Setting temperature using Fahrenheit
console.log(`86°F is equivalent to ${temp.celsius.toFixed(2)}°C.`); // Showing updated Celsius using the setter

Private Fields

Private fields (or private properties) are properties that are only accessible from within a class. To create a private field, use a hash (#) in front of the variable declaration.

class Counter {
  #count = 0;
  increment() {
    this.#count++;
  }
  get value() {
    return this.#count;
  }
}
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH