Prototypes

The prototype mechanism in JavaScript is quite complicated. We will only glance at it here. You will want to spend plenty of time reviewing Chapters 4-6 of the this & Object Prototypes title of this series for all the details.

When you reference a property on an object, if that property doesn’t exist, JavaScript will automatically use that object’s internal prototype reference to find another object to look for the property on. You could think of this almost as a fallback if the property is missing.

The internal prototype reference linkage from one object to its fallback happens at the time the object is created. The simplest way to illustrate it is with a built-in utility called Object.create(..).

Consider:

  1. var foo = {
  2. a: 42
  3. };
  4. // create `bar` and link it to `foo`
  5. var bar = Object.create( foo );
  6. bar.b = "hello world";
  7. bar.b; // "hello world"
  8. bar.a; // 42 <-- delegated to `foo`

It may help to visualize the foo and bar objects and their relationship:

Prototypes - 图1

The a property doesn’t actually exist on the bar object, but because bar is prototype-linked to foo, JavaScript automatically falls back to looking for a on the foo object, where it’s found.

This linkage may seem like a strange feature of the language. The most common way this feature is used — and I would argue, abused — is to try to emulate/fake a “class” mechanism with “inheritance.”

But a more natural way of applying prototypes is a pattern called “behavior delegation,” where you intentionally design your linked objects to be able to delegate from one to the other for parts of the needed behavior.

Note: For more information about prototypes and behavior delegation, see Chapters 4-6 of the this & Object Prototypes title of this series.