DevPath · Learn to code ESPTEN

Object-oriented programming

Classes, constructor and methods

Classes

A class is a template to create objects of the same type. It defines what data they will have (in the constructor) and what they can do (the methods).

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

  greet() {
    return `Hi, I'm ${this.name}`;
  }
}

const ana = new Person("Ana", 30);
console.log(ana.greet()); // "Hi, I'm Ana"

Prototypes: what lies underneath

Classes are a more convenient syntax over JavaScript's prototype system. Methods are not copied into each object: they live in a shared object (the prototype) and every instance consults it. That is why creating a thousand people does not duplicate the greet method a thousand times.

Examples

Defining a class and creating instances

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() {
    return this.width * this.height;
  }
}
const r = new Rectangle(4, 3);
console.log("Area:", r.area());
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Objects and thisInheritance and encapsulation →