Hiprup

What is the class syntax in JavaScript?

Classes are a cleaner syntax over JavaScript's prototype-based inheritance — "syntactic sugar" that's easier to read.

  • constructor — runs when you create an instance with new and sets up initial properties.

  • Methods — shared by all instances via the prototype.

  • extends / super — create subclasses and call the parent's constructor or methods.

  • static — methods or fields that belong to the class itself, not instances.

Under the hood: it's still prototypes — classes don't add a new inheritance model.

class Animal {
  #sound;  // Private field (ES2022)

  constructor(name, sound) {
    this.name = name;  // Public
    this.#sound = sound; // Private
  }

  speak() {  // Instance method (on prototype)
    return `${this.name} says ${this.#sound}`;
  }

  get info() {  // Getter
    return `${this.name} (${this.constructor.name})`;
  }

  static create(name, sound) {  // Static method
    return new this(name, sound);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name, 'Woof');  // Call parent constructor
    this.breed = breed;
  }

  fetch(item) {
    return `${this.name} fetches ${item}`;
  }

  speak() {  // Override parent
    return `${super.speak()}! (${this.breed})`;
  }
}

const dog = new Dog('Rex', 'Labrador');
console.log(dog.speak());      // 'Rex says Woof! (Labrador)'
console.log(dog.info);          // 'Rex (Dog)'
console.log(dog.fetch('ball')); // 'Rex fetches ball'
console.log(Dog.create('Buddy', 'Golden')); // Static factory

// Private field
// console.log(dog.#sound); // SyntaxError! Private
console.log(dog instanceof Animal); // true

constructor initializes the instance. # prefix makes fields truly private (SyntaxError if accessed outside the class). static methods are called on the class (Dog.create), not instances. extends sets up prototype chain. super() calls parent constructor, super.speak() calls parent method. Getters (get info) are accessed like properties.

Show constructor, methods, static, private (#), extends, and super. Know that classes are sugar over prototypes (typeof Dog === 'function').

Private fields (#) are truly private (not just convention). static for factory methods. instanceof works through the prototype chain.

What is the class syntax in JavaScript? | Hiprup