Skip to content
jshacks.dev
Patterns

OOP in JavaScript Objects Classes and Prototypes

Learn how object-oriented programming works in JavaScript, from object literals and prototypes to classes, with the four OOP ideas shown in code with output.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js and npm logos.

Object-oriented programming in JavaScript is different from the version taught for Java or C#, and the difference trips up people moving between languages. Java classes are blueprints that stamp out instances, and the class is a separate kind of thing from the object. In JavaScript, objects can be created directly with no class, inheritance is a link between live objects called the prototype chain, and the class keyword added in ES2015 is a cleaner syntax over that same machinery. This post explains OOP in JavaScript from the ground up in Node.js 24: objects, methods, the prototype chain, classes, and how the four usual OOP ideas, encapsulation, abstraction, inheritance and polymorphism, look in each. Every example prints its output, and each section links to a deeper post.

Objects come first

In JavaScript you do not need a class to have an object. An object literal is a collection of properties, some of which are functions, and those functions are methods.

literal.mjsJavaScript
const account = {
  owner: "Ada",
  balance: 100,
  deposit(amount) {
    this.balance += amount;
    return this;
  },
};

account.deposit(50);
console.log(account.balance);
Text
150

The method uses this, which refers to the object the method was called on. That detail matters: this is decided by how a function is called, not where it is defined, so const f = account.deposit; f(50) loses the object and fails. Arrow functions are the exception, since they keep the this of the place where they were written.

The prototype chain

Every object has an internal link to another object, its prototype. When you read a property that the object does not have, JavaScript looks at the prototype, then the prototype's prototype, until it finds the property or reaches the end of the chain, which is null.

prototype.mjsJavaScript
const animal = {
  speak() {
    return `${this.name} makes a sound`;
  },
};

const dog = Object.create(animal);
dog.name = "Rex";

console.log(dog.speak());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.hasOwn(dog, "speak"));
Text
Rex makes a sound
true
false

dog has no speak method of its own, so the lookup finds it on animal. this inside the method is still dog, which is why the name is "Rex". This is delegation: the object forwards unknown requests along the chain. Everything in JavaScript inheritance, including classes, is built on this one mechanism.

Classes are syntax over prototypes

The class keyword gives you a compact way to set up a constructor and a shared prototype.

class.mjsJavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

const cat = new Animal("Tom");
console.log(cat.speak());
console.log(typeof Animal);
console.log(Object.getPrototypeOf(cat) === Animal.prototype);
Text
Tom makes a sound
function
true

The class is a function, and speak lives on Animal.prototype, shared by every instance, rather than copied into each one. That is why methods are cheap. The difference from older constructor functions is mostly syntax and a few safeguards: a class cannot be called without new, its body runs in strict mode and its methods are not enumerable.

The four OOP ideas

Encapsulation means keeping an object's internal state hidden behind a controlled interface. Modern JavaScript has true private fields, written with #, which cannot be accessed outside the class body.

encapsulation.mjsJavaScript
class Counter {
  #count = 0;
  increment() {
    return ++this.#count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.increment());
console.log(counter.count);
Text
2
undefined

The count is reachable only through methods. A deeper comparison of private fields and closures is in encapsulation in JavaScript.

Abstraction means exposing what something does and hiding how. A function or method with a clear name and a stable signature is an abstraction, and so is a class whose public methods describe behavior in the problem's terms, not the implementation's. JavaScript has no interface keyword, so abstraction relies on convention and, in TypeScript, on interfaces and abstract classes.

Inheritance lets one class build on another with extends and super.

inheritance.mjsJavaScript
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  speak() {
    return `${super.speak()}: woof`;
  }
}

console.log(new Dog("Rex").speak());
Text
Rex makes a sound: woof

Dog.prototype links to Animal.prototype, so the chain is dog to Dog.prototype to Animal.prototype to Object.prototype. See inheritance in JavaScript for the details and for the traps.

Polymorphism means different objects respond to the same call in their own way. JavaScript gets it from duck typing: any object with a speak method can be used where one is expected, with no shared base class required.

polymorphism.mjsJavaScript
const speakers = [
  { speak: () => "meow" },
  { speak: () => "woof" },
  new (class Robot {
    speak() {
      return "beep";
    }
  })(),
];

console.log(speakers.map((s) => s.speak()));
Text
[ 'meow', 'woof', 'beep' ]

Three unrelated objects answer the same message. This flexibility is a strength and a risk, because a missing method is found at runtime, which is the gap TypeScript's structural types close.

Alternatives to class-based design

Because JavaScript has functions as values and objects without classes, other styles are common. A factory function returns an object that closes over private variables.

factory.mjsJavaScript
function createCounter() {
  let count = 0;
  return {
    increment: () => ++count,
  };
}

const counter = createCounter();
counter.increment();
console.log(counter.increment());
Text
2

Composition, building objects by combining small behaviors, often beats inheritance for flexibility, as discussed in composition over inheritance in JavaScript. Many successful codebases mix styles: classes where identity and state matter, plain functions and data elsewhere.

Common stumbling blocks

Four things catch learners. Method extraction loses this, as noted above, so pass an arrow function or bind the method when you hand it to a callback. Class fields defined with arrow functions give each instance its own copy of the method, which costs memory but keeps this fixed. Inheritance depth grows unnoticed, and a hierarchy of four or five levels is a sign to prefer composition. And instanceof checks the prototype chain, so objects created across realms, such as iframes, can fail it.

Prototype mutation is the last trap. Because instances share the prototype, adding to Animal.prototype after the fact changes every instance, including existing ones. That is powerful for polyfills and dangerous in application code, where modifying a built-in prototype such as Array.prototype can break libraries that did not expect the new property.

Where the advice stops

None of this means you must write object-oriented code in JavaScript. React moved from classes to function components, and many Node.js services are mostly modules of functions with plain data. Use classes when you have long-lived objects with state and identity, such as a connection, a parser or a domain entity, and use functions when you transform data. The skill is knowing how both work, since libraries you depend on use each.

Checking what you have

Two small built-ins help when you are unsure how an object is put together. Object.getPrototypeOf(value) shows the next link in the chain, and Object.getOwnPropertyNames(value) lists what the object holds itself, as opposed to what it inherits. Printing both for a class instance and for its prototype is the quickest way to see where a method actually lives. When a method is missing or an override does not take effect, the cause is almost always visible there: the method was defined on the instance and shadows the prototype's version, or it was defined on a different prototype than you thought.

The instanceof operator answers a related question, whether the prototype of a constructor appears anywhere in an object's chain. It works for classes and for older constructor functions alike. For duck-typed code, prefer checking for the method you need, such as typeof value.speak === "function", because it does not depend on how the object was built and so does not break when two copies of a library create look-alike classes.

Moving from classical OOP

Developers who come from Java or C# bring habits that do not all transfer. Interfaces and abstract classes are not enforced at runtime, so a missing method fails when called, not when the class is declared. Overloading by parameter type does not exist, and a method is chosen by name only, so you check argument types or use an options object. Access modifiers other than # are conventions: a leading underscore is a hint, not a barrier. And static typing is optional, which is why many teams add TypeScript to recover the compile-time checks they are used to, while keeping JavaScript's flexibility where it helps.

The most useful adjustment is to treat inheritance as one tool among several. In JavaScript it is easy to build an object by combining functions or by delegating to another object, and doing so avoids the fragile base class problem, in which a change to a parent class breaks children in ways nobody predicted. Start with the simplest structure that works, and add a class hierarchy only when you have several kinds of object that really share state and behavior.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.