How to Create a JavaScript Class: A Comprehensive Guide

What is a JavaScript Class?

A JavaScript class is a blueprint for creating objects. It defines a set of properties and methods that an object will have. Classes provide a way to create reusable code and organize your application’s logic.

Basic Syntax of a JavaScript Class

Here’s the basic syntax for creating a JavaScript class:

// Define a class
class MyClass {
  // Constructor method
  constructor() {
    // Initialization code
  }

  // Method
  myMethod() {
    // Method implementation
  }
}

// Create an instance of the class
const myInstance = new MyClass();
// Call the method
myInstance.myMethod();

Properties in a JavaScript Class

Properties are variables that hold data. You can define properties inside the constructor method or directly in the class.

Example 1: Properties Inside the Constructor

// Define a class with properties
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

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

// Create an instance
const person = new Person('John', 'Doe');
console.log(person.getFullName()); // Output: John Doe

Example 2: Properties Directly in the Class

// Define a class with properties
class Car {
  make = 'Toyota';
  model = 'Corolla';

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

// Create an instance
const car = new Car(2023);
console.log(car.make); // Output: Toyota

Methods in a JavaScript Class

Methods are functions that perform actions. They can be instance methods (called on instances) or static methods (called on the class itself).

Example 3: Instance Methods

// Define a class with methods
class Calculator {
  constructor() {
    this.result = 0;
  }

  add(number) {
    this.result += number;
  }

  subtract(number) {
    this.result -= number;
  }
}

// Create an instance
const calculator = new Calculator();
calculator.add(5);
console.log(calculator.result); // Output: 5

Example 4: Static Methods

// Define a class with static methods
class MathUtils {
  static add(a, b) {
    return a + b;
  }

  static multiply(a, b) {
    return a * b;
  }
}

// Call static methods
console.log(MathUtils.add(2, 3)); // Output: 5
console.log(MathUtils.multiply(2, 3)); // Output: 6

Constructors in JavaScript Classes

The constructor method is a special method that is called when an instance of the class is created. It is used to initialize the properties of the object.

Example 5: Constructor with Default Values

// Define a class with a constructor
class Book {
  constructor(title, author = 'Unknown') {
    this.title = title;
    this.author = author;
  }
}

// Create instances
const book1 = new Book('The Great Gatsby');
console.log(book1.author); // Output: Unknown

const book2 = new Book('To Kill a Mockingbird', 'Harper Lee');
console.log(book2.author); // Output: Harper Lee

Inheritance in JavaScript Classes

JavaScript classes support inheritance using the extends keyword. This allows you to create a hierarchy of classes where a subclass inherits properties and methods from a superclass.

Example 6: Inheritance

// Define a superclass
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `My name is ${this.name}`;
  }
}

// Define a subclass
class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    return `${super.speak()} and I am a ${this.breed}`;
  }
}

// Create an instance of the subclass
const dog = new Dog('Buddy', 'Golden Retriever');
console.log(dog.speak()); // Output: My name is Buddy and I am a Golden Retriever

Getters and Setters in JavaScript Classes

Getters and setters are methods that allow you to control access to properties. They are defined using the get and set keywords.

Example 7: Getters and Setters

// Define a class with getters and setters
class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get radius() {
    return this._radius;
  }

  set radius(value) {
    if (value < 0) {
      throw new Error('Radius cannot be negative');
    }
    this._radius = value;
  }
}

// Create an instance
const circle = new Circle(5);
console.log(circle.radius); // Output: 5

// Try to set a negative radius
try {
  circle.radius = -3;
} catch (error) {
  console.error(error.message); // Output: Radius cannot be negative
}

Static Properties in JavaScript Classes

Static properties are properties that are defined on the class itself rather than on instances of the class. They are accessed using the class name.

Example 8: Static Properties

// Define a class with static properties
class Constants {
  static PI = 3.14159;
  static GRAVITY = 9.81;
}

// Access static properties
console.log(Constants.PI); // Output: 3.14159
console.log(Constants.GRAVITY); // Output: 9.81

Private Fields in JavaScript Classes

Private fields are properties that are only accessible within the class. They are defined using the # symbol.

Example 9: Private Fields

// Define a class with private fields
class BankAccount {
  #balance = 0;

  constructor(initialBalance) {
    if (initialBalance > 0) {
      this.#balance = initialBalance;
    }
  }

  getBalance() {
    return this.#balance;
  }

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }
}

// Create an instance
const account = new BankAccount(1000);
console.log(account.getBalance()); // Output: 1000

// Try to access the private field directly
console.log(account.#balance); // This will throw an error

Frequently Asked Questions

1. What is the difference between a class and an object in JavaScript?

A class is a blueprint for creating objects, while an object is an instance of a class. The class defines the properties and methods that the object will have, and the object is the actual instance of the class that you work with.

2. Can I create multiple instances of a JavaScript class?

Yes, you can create as many instances of a class as you need by using the new keyword followed by the class name.

3. What is the purpose of the constructor method?

The constructor method is called automatically when an instance of the class is created. It is used to initialize the properties of the object.

4. How do I inherit from a class in JavaScript?

You can inherit from a class using the extends keyword. The subclass will inherit all the properties and methods of the superclass, and can add its own properties and methods as well.

5. What is the difference between static and instance methods?

Static methods are called on the class itself, while instance methods are called on instances of the class. Static methods cannot access the instance-specific properties or methods, while instance methods can.

Conclusion

Creating a JavaScript class is a powerful way to organize your code and create reusable components. By defining properties, methods, constructors, and static members, you can create classes that encapsulate the behavior of objects in your application. With the addition of modern JavaScript features like private fields and getters/setters, you can create classes that are both robust and maintainable.

Index
Scroll to Top