Free beginner tutorial

JavaScript Classes: Constructors and Methods

A JavaScript class describes a reusable kind of object. Use a constructor to set up each instance, then add methods for behavior those instances share.

Define a class

This Product class stores a name and price. The constructor runs when you create an instance with new:

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  describe() {
    return `${this.name} costs ${this.price.toFixed(2)}.`;
  }
}

const notebook = new Product("Notebook", 4.5);
console.log(notebook.describe());

The console displays Notebook costs $4.50.. Inside describe(), this refers to the instance that received the method call.

Create more than one instance

Use the same class to create objects with different data and the same behavior:

const pen = new Product("Pen", 1.25);
const folder = new Product("Folder", 3.75);

console.log(pen.describe());
console.log(folder.describe());

Each instance has its own name and price. Both can use the describe() method defined by the class.

Class or plain object?

A plain object is a good fit for one record of related values. A class is useful when you need to create many similar objects that share setup and behavior. For a small one-off value, a class can add unnecessary complexity.

Common class mistakes

  • Use new Product(...) to create an instance. A class constructor cannot be called like a regular function.
  • Write constructor with that exact spelling so JavaScript recognizes the initializer.
  • Use this.propertyName to store or read instance data in a class method.
  • Choose clear class names such as Product and clear method names such as describe.

Try it yourself

Create a Book class with a title and author, then add a method that returns a sentence about the book. Make two instances with different details and call the method on each.

Classes provide a reusable way to create objects. For one object with a few values, a plain object literal is often simpler.