Prototypal inheritance

Here's the prototypal inheritance pattern suggested by Douglas Crockford.

The implementation looks similar to a classical pattern but the idea is very different.

The idea is that there’s no constructors involved that lead you to think in terms of classes.
You have an object and you want to create another object that gets functionality from the existing object.

And, unlike when we simply copied properties over from the parent, here we involve the prototype and keep the prototype chain.

function object(o) {
  function F(){}
  F.prototype = o;
  return new F();
}

We take an existing object o, create a blank constructor function and set the parent object o to be the prototype.

Then return an object created with the temporary constructor. This child object has all properties of the parent as part of the prototype.

And here’s an example usage:

>>> var parent = {a: 1};
>>> var child = object(parent);
>>> child.a;
1
>>> child.hasOwnProperty(a);
false

The child object has everything the parent has - not as its own properties but as properties of its prototype.

ECMAScript 5

In the proposed version 5 of the ECMAScript standard, there will be a method that will work similarly and also accept another object, so basically you'll be able to inherit and add more functionality at the same time.

var child = Object.create(parent, {more:1})

Tags: , ,

2 Responses to “Prototypal inheritance”

  1. criminal records Says:

    arrest records…

    [...]JSPatterns.com » Blog Archive » Prototypal inheritance[...]…

  2. Buy Facebook Fans Says:

    Sources…

    [...]here are some links to sites that we link to because we think they are worth visiting[...]…

Leave a Reply