Prototypes and Object.create

Every object delegates to another object via its prototype; Object.create sets that link up explicitly.

                Object.create(proto) / Object.getPrototypeOf(obj)
              

Purpose

Every object has an internal link to another object β€” its prototype β€” that it delegates to. Reading a property not found directly on an object continues the search up this prototype chain. Object.create(proto) creates a new object with an explicit prototype link.

Syntax

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

const dog = Object.create(animal);
dog.name = 'Rex';
console.log(dog.speak()); // "Rex makes a sound." β€” found via the prototype chain
console.log(Object.getPrototypeOf(dog) === animal); // true

Behavior notes

  • A property defined directly on an object shadows a same-named one further up the chain β€” the search stops at the first match.
  • Array methods (map, filter, …) live on Array.prototype, not on each array instance β€” this is why every array can call them without the methods being copied onto each one individually.
  • Object.create(null) produces an object with no prototype at all β€” useful for a plain lookup map with no inherited properties (no toString, no risk of a key colliding with an inherited name).
  • Older code achieves this same delegation with a constructor function and new (function Animal() {}, Animal.prototype.speak = …) β€” the historical predecessor to classes, producing an identical prototype-chain structure.

Common mistakes

  • Assuming each object gets its own copy of a prototype method β€” it doesn’t; every delegating object shares the exact same method, found via the chain each time.
  • Mutating a shared prototype object directly when only one specific object’s behavior should change β€” this affects every object delegating to that prototype.

Runtime notes

The prototype mechanism is core ECMAScript, identical across every current browser and Node version.

Taught in these lessons

Related reference