Skip to content
Theory · Classes and prototypes · lesson 1 of 12

Classes

What you'll learn

What you'll learn:

  • describe objects of one kind with a class and create them with new;
  • compute a property with a getter, hide data in a private # field and create objects with a static method;
  • build a subclass with extends and call the parent through super;
  • explain where methods live and how JavaScript finds them along the prototype chain.
A chair blueprint User and two chairs built from it in different colours, tagged ann and tom

Picture a furniture factory. An engineer draws the blueprint of a chair once: its legs, seat and back, and how to put it together. From this blueprint the workshop builds hundreds of chairs. Each one has its own color, but they are all made the same way.

A program works the same way: there are many users, products or orders, and they all have the same properties and actions. A function that builds an object from its parameters describes the object anew on every call: each property and each method. When there are many similar objects, it is handier to describe their common shape once, with a class. The class is the blueprint, and the objects are the chairs built from it:

JavaScript
class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    isAdult() {
        return this.age >= 18;
    }
}

const ann = new User("Ann", 30);
const tom = new User("Tom", 12);
console.log(ann.name, ann.isAdult()); // Ann true
console.log(tom.name, tom.isAdult()); // Tom false

Let's walk through the example:

  1. class User { … } is the blueprint: every user will have the properties name and age and the method isAdult.
  2. new User("Ann", 30) builds the first object from the blueprint, and new User("Tom", 12) builds the second.
  3. The first console.log prints Ann true: the age of ann is 30, which is at least 18.
  4. The second prints Tom false: the same method answers differently for tom, who is 12.

Class and instance

A class describes objects of one kind: which properties and methods they have. An object created from a class is called an instance: ann and tom are two instances of the class User. By convention, a class name starts with a capital letter.

A class body looks like an object literal, but it has its own rules:

  • methods are written without the word function;
  • there are no commas between methods;
  • the method named constructor fills in each new object.

What new does

The new operator creates an instance. Let's take the expression new User("Ann", 30) step by step:

  1. new creates a new empty object.
  2. Then it calls the constructor method with the arguments "Ann" and 30.
  3. Inside constructor, the word this means this new object, so this.name = name writes the property name into it, and this.age = age writes the property age.
  4. new returns the finished object, and it lands in the constant ann.

Under the hood, a class is a special function: typeof User gives "function". But it can be called only through new: the common mistake at the end of the lesson shows what happens without it.

Methods shared by all

The isAdult method is shared by all instances: it is not copied into each object. In the call tom.isAdult(), this is tom, as with any method called through a dot. That is why each instance answers about its own age.

Here the factory analogy stops working. A finished chair lives on its own and no longer needs the blueprint. An instance, though, keeps using the class's methods: they live in one place, and every instance reaches for them there.

Fields

A property can be declared right in the class body, outside constructor: count = 0;. Such a property is called a field. Each instance gets its own field with the starting value, even before the body of constructor runs. If there are no other properties, constructor can be left out entirely.

JavaScript
class Counter {
    count = 0;

    increment() {
        this.count++;
        return this.count;
    }
}

const a = new Counter();
const b = new Counter();
a.increment();
console.log(a.increment(), b.count); // 2 0

Let's see what happens to the counters:

  1. Both calls new Counter() create objects with their own field count, equal to 0.
  2. The first call a.increment() raises a.count to 1.
  3. The second call, inside console.log, raises it to 2 and returns 2.
  4. b.count is still 0: a method changes the field of the object it was called on.

Strict mode in a class

A class body always runs in strict mode, even without the line "use strict". If a method assigns a value to a misspelled variable name, the program stops with a ReferenceError, and no global variable appears. That way you see the typo at once, not after an hour of searching.

Common mistake

A class was called without new, like an ordinary function:

JavaScript
const bob = User("Bob", 20); // ✗
TEXT
TypeError: Class constructor User cannot be invoked without 'new'

This is the Node.js and Chrome message. An ordinary function would run without new too, but a class forbids such a call and stops the program at once. An instance is created only through new: new User("Bob", 20).

Key points

  • A class describes objects of one kind once, and new builds instances from it.
  • new creates an empty object, calls constructor with this set to that object, and returns the object.
  • Class methods are shared by all instances, while each instance has its own fields.
  • A class is called only through new, and its body always runs in strict mode.

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way