Next →

Classes and Prototypes in JavaScript

JavaScript uses prototypes for inheritance, but ES6 introduced the class syntax to make working with objects and inheritance simpler and more intuitive.

Classes

A class is a blueprint for creating objects with properties and methods.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const person1 = new Person("Alice", 30);
person1.greet();  // Hello, my name is Alice

Prototypes

Every JavaScript object has a prototype, which is another object from which it inherits methods and properties.

Before classes, this was how inheritance was handled:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function() {
  console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person("Bob");
person1.greet(); // Hello, my name is Bob