JavaScript Classes

Classes are a template for creating objects, bundling data and the functions that operate on it into a reusable blueprint.

What is a class?

A class is a blueprint for building objects that share the same shape and behavior. Instead of writing the same properties and methods over and over, you define them once in a class and then create as many objects (called instances) from it as you need. Classes were introduced in ES6 (2015) and give JavaScript a cleaner, more familiar syntax for object-oriented programming.

Note: Under the hood, JavaScript classes are built on the older prototype system. The class keyword is mostly a friendlier syntax over that mechanism, not an entirely new object model.

Defining a class and the constructor

You declare a class with the class keyword followed by a name (conventionally capitalized). Most classes include a special method called constructor, which runs automatically whenever a new object is created with the new keyword. The constructor is where you set up the object's initial properties, using the this keyword to refer to the instance being built.

A basic class with a method

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Classes</h2>

<script>
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    return "Hi, I'm " + this.name;
  }
}

const ada = new Person("Ada", 36);
console.log(ada.greet()); // "Hi, I'm Ada"
console.log(ada.age);     // 36
</script>

</body>
</html>

Methods, getters, and static members

  • Instance methods are shared functions available on every object created from the class.
  • Getters (get) let you read a computed value as if it were a plain property.
  • Static methods (static) belong to the class itself, not to instances, and are called on the class name.
  • Fields can hold default values and, when prefixed with #, become truly private to the class.

Getters, static methods, and private fields

<!DOCTYPE html>
<html>
<body>

<h2>Getters, Static Methods, and Private Fields</h2>

<script>
class Circle {
  #radius;              // private field

  constructor(radius) {
    this.#radius = radius;
  }

  get area() {          // used like circle.area
    return Math.PI * this.#radius ** 2;
  }

  static fromDiameter(d) {
    return new Circle(d / 2);
  }
}

const c = Circle.fromDiameter(10);
console.log(c.area.toFixed(2)); // "78.54"
</script>

</body>
</html>

Creating several instances from one class

<!DOCTYPE html>
<html>
<body>

<h2>Creating Instances</h2>

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

  withTax(rate = 0.2) {
    return this.price * (1 + rate);
  }
}

const items = [
  new Product("Pen", 2),
  new Product("Notebook", 5)
];

items.forEach((p) => {
  console.log(p.name + ": " + p.withTax());
});
// Pen: 2.4
// Notebook: 6
</script>

</body>
</html>
MemberBelongs toExample call
constructorRuns on creationnew Person(...)
Instance methodEach objectada.greet()
GetterEach objectcircle.area
Static methodThe classCircle.fromDiameter(10)
Note: Class declarations are not hoisted the way function declarations are. You must define a class in the code before you try to create instances from it, or you will get a reference error.

Exercise: JavaScript Classes

In a subclass constructor, what must happen before you can use `this`?