2 Inheritance-based object modeling

 

This chapter covers

  • Prototypal inheritance, constructor functions, and classes
  • JavaScript’s property resolution mechanism
  • The “prototypal inheritance” oxymoron
  • Advantages and drawbacks of classes in JavaScript

Merely adding “prototypal” in front to distinguish the actually nearly opposite behavior in JavaScript has left in its wake nearly two decades of miry confusion.

—Kyle Simpson

Aside from a few primitives, everything in JavaScript is an object. Yet for something that we deal with routinely, objects continue to be the most intimidating, hard-to-get-right parts of the language. The most common question that I hear is “How should I write the prototype chain to relate X, Y, and Z?” Every article or book you read does it in slightly different ways, and for some reason, even experienced developers need to turn to a search engine to relearn the process once in a while. The reason is twofold: on one side, a lot of boilerplate code is required, and on the other, we’re confusing the terms inheritance and prototype.

2.1 Reviewing prototypal inheritance

2.1.1 Property resolution process

2.1.2 Differential inheritance

2.2 Constructor functions

2.2.1 Functions as templates

2.2.2 Sharing properties by using constructors and prototypes

2.3 Class-based inheritance

Summary