Posts Tagged ‘prototype’

Prototypal inheritance

Tuesday, September 15th, 2009

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})

Prototype

Monday, September 14th, 2009

The prototype is an object that every function gets automatically, as soon as you create it.

You can add properties and methods to the prototype property of your constructor function. Then all objects created with this constructor will have access to everything you add to the prototype.

var Person = function(name) {
  this.name = name;
};
Person.prototype.say = function() {
  return this.name;
};

if you add properties to the prototype of a "normal" function, meaning function that you don't invoke as a constructor, these will not be used.

Using the prototype

var adam = new Person('Adam');
alert(adam.name); // "Adam"
alert(adam.say()); // "Adam"

As you can see the object has access to the prototype’s members.

The prototype properties are shared among all objects.

Rule of thumb

And a general rule of thumb – the properties and methods that are meant to be reused and shared and inherited, should be added to the prototype.