liveBook · Manning

Prototype-based object orientation

As explained in JavaScript in Depth

A JavaScript inheritance model in which objects delegate property lookup to linked prototype objects rather than copying properties or relying on class-based inheritance.

JavaScript shares behavior through live links between objects. If a property is missing, lookup walks the prototype chain until it finds the property or reaches the chain’s end. The prototype is not copied, so multiple objects can reference the same behavior and observe later prototype changes. section 5.3

This inheritance model remains dynamic at runtime: modifying a shared prototype affects its inheriting objects, and changing an object’s prototype changes where subsequent lookups search. It shares methods without using classes or duplicating method definitions. section 5.3

A method found on a prototype still receives the original object as this. One shared method can therefore read and update each object’s own properties, such as a drawer’s label or open state. section 5.4.2

const drawerPrototype = {
  open() { console.log('Opening drawer'); }
};
const drawer1 = Object.create(drawerPrototype);
const drawer2 = Object.create(drawerPrototype);
drawer1.open();
drawer2.open();

Creates two drawer objects with Object.create() and demonstrates both delegating open() to one shared prototype. section 5.3

const drawerPrototype = {
  open() {
    console.log(`Opening the ${this.label} drawer`);
    this.isOpen = true;
  }
};
 
const drawer1 = Object.create(drawerPrototype);
drawer1.label = 'tax documents';
 
const drawer2 = Object.create(drawerPrototype);
drawer2.label = 'receipts';
 
drawer1.open();  #A
 
drawer2.open();  #B

Shows one inherited method using this to act on different objects and their instance-specific properties. section 5.4.2

How JavaScript in Depth covers it

How deep it goes
Traces prototype lookup, live mutation, reassignment, and this binding, but does not detail runtime implementation internals.
Examples
Uses shared drawer prototypes, open and close methods, changing prototypes, and labels stored on individual drawer objects.
What you can do after
Apply prototype inheritance with Object.create(), modify shared prototypes, change prototype links, and preserve receiver-specific this behavior.
How it connects
Connects prototype chains with property lookup, Object.create(), Object.setPrototypeOf(), methods, and this binding.

Also explained in

Compare how 4 books explain prototype-based object orientation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.