LibraryJavaScriptClasses and Prototypes

Classes and Prototypes

Understand JavaScript's prototype model and use classes when instances share behavior.

Updated Tested with ECMAScript 2026

JavaScript objects inherit behavior through prototype chains. Class syntax is a clearer way to define constructors and shared prototype methods.

Define an instance contract

course.js
class Course {
  #completed = 0;

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

  completeLesson() { this.#completed += 1; }
  get progress() { return this.#completed / this.lessonCount; }
}

const html = new Course("HTML", 14);

Methods are shared through Course.prototype. Private fields are inaccessible outside the class body.

Composition before inheritance

Inheritance with extends can model a true subtype, but deep class trees couple behavior tightly. Small functions and composed objects are often easier to test.

composition.js
const withProgress = (lessonCount) => ({ completed: 0, lessonCount });
const course = { title: "CSS", progress: withProgress(18) };

Keep this

Know that classes use prototypes, keep instance state intentional, and prefer composition unless inheritance expresses a real relationship.

Your place is saved on this device.