liveBook · Manning

Prototype-based object orientation

As explained in Secrets of the JavaScript Ninja, Third Edition

Prototypal inheritance is an inheritance model in which objects obtain properties and methods through links to other objects.

JavaScript objects can inherit properties and methods through links to other objects, rather than relying solely on class-based inheritance. A constructor function’s `prototype` supplies the prototype for objects created with `new`; arrow functions cannot be used as constructors. section 1.1 section 9.3.2

Listing 9.5 Creating a new instance with a prototyped method
function Ninja() {} #A
 
Ninja.prototype.swingSword = () => true; #B
 
// @ts-expect-error -- Ninja has no construct signature #C
const ninja = new Ninja(); #D
console.assert( #D
  ninja.swingSword() === true, #D
  "swingSword is inherited from the prototype.", #D
); #D
console.assert( #E
  ninja instanceof Ninja, #E
  "instanceof confirms that ninja is a Ninja", #E
); #E

A constructor adds `swingSword` to its prototype; the new object inherits the method, and `instanceof` checks its relationship to the constructor. section 9.3.2

Inherited properties act as fallbacks when an object lacks the property itself. Even `{}` has a prototype—`Object.prototype`—while `Object.create(null)` makes an object with no prototype. JavaScript’s `class` syntax uses prototypes under the hood. section 9.3.2 section 1.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Traces constructor-created prototype links, inherited-property fallback, and prototype-free objects, without detailing the full inheritance model.
Examples
Demonstrates an inherited Ninja method, `{}` inheriting `toString`, and `Object.create(null)` lacking that method.
What you can do after
Build a constructor-created object that inherits a method from its constructor’s prototype.
How it connects
Links prototypes to constructors, functions, classes, Object.prototype, and TypeScript.

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 Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.