Codeskill

Learn to code, step by step

Classes and prototypes

Classes and prototypes in JavaScript – enough to read and write modern code confidently, without diving into every edge case of the inheritance model.

Prototypes under the hood

Every object has an internal prototype link. When you read obj.foo and obj has no own property foo, the engine looks on the prototype chain. That is how shared methods work.

const animal = {
  speak() {
    return '...';
  },
};

const dog = Object.create(animal);
dog.speak = function () {
  return 'woof';
};

You rarely write Object.create by hand today, but you will see prototype language in docs and debuggers. Classes are syntax sugar over this model.

Class syntax

class TodoItem {
  #done = false;

  constructor(title) {
    this.title = title;
  }

  toggle() {
    this.#done = !this.#done;
  }

  get isDone() {
    return this.#done;
  }
}

The constructor runs on new. Methods live on the prototype. Private fields (#done) stay inside the class – a recent but useful addition for encapsulation.

extends and super

class PriorityTodo extends TodoItem {
  constructor(title, priority) {
    super(title);
    this.priority = priority;
  }

  label() {
    return `[${this.priority}] ${this.title}`;
  }
}

super must be called in the subclass constructor before you use this. super.method() calls the parent implementation.

Static members

Static methods belong to the class, not instances – factories, parsers, constants.

class User {
  static fromJSON(data) {
    return new User(data.id, data.name);
  }
}

const user = User.fromJSON({ id: 1, name: 'Sam' });

When to use a class

  • Several instances share behaviour and internal state – widgets, models, game entities.
  • You want a clear constructor and method list for readers.
  • You are consuming a library that expects class instances.

When a plain object plus functions suffices, skip the ceremony. Not everything needs new.

instanceof and custom types

item instanceof TodoItem; // true if prototype chain matches

Prefer type checks at system boundaries (parsing API data) rather than scattering instanceof everywhere.

Next: async patterns – errors, cancellation, and not launching fifty requests at once.

PreviousClosures, this, and binding