Class

An ES6 feature that provides a cleaner, more intuitive syntax for creating objects and implementing inheritance in JavaScript, built on top of prototypal inheritance.

Overview

Classes are templates for creating objects in JavaScript. Introduced in ES6, they provide syntactic sugar over JavaScript's existing prototype-based inheritance. Classes make it easier to create objects with shared methods and implement object-oriented programming patterns.

Example

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

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

  static create(name, age) {
    return new Person(name, age);
  }
}

// Inheritance
class Developer extends Person {
  constructor(name, age, language) {
    super(name, age);
    this.language = language;
  }

  code() {
    return `${this.name} codes in ${this.language}`;
  }
}

const dev = new Developer('Alice', 30, 'JavaScript');
dev.greet(); // "Hello, I'm Alice"
dev.code();  // "Alice codes in JavaScript"

Key Points

  • Syntactic sugar over prototypes
  • constructor method for initialization
  • extends keyword for inheritance
  • super() calls parent constructor
  • Static methods belong to class, not instances

Learn More