David Jones

The prototype pattern

The "Gang of Four" describe the prototype pattern as one which creates objects based on the template of an existing object through cloning.

The prototype object can be compared to a blueprint. Every object that the constructor creates will be a clone of the prototype object. So if the prototype object has a property called email the cloned object will have a property of the same name.

So why should we use prototypes?

Using a prototype results in faster object creation. This is because the functions do not have to be re created multiple times because they are already available in the prototype.

Using a prototype also give you the ability to edit every object that uses the prototype. This could be by adding a method or property.

Lets look at a simple example.

var Vehicle = function() {
    this.name = 'name';
    this.type = 'type';
    this.speed = '50mph';

    return this;

var Car = function() {
    this.name = 'hummer';
    this.type = 'car';

    return this;

Car.prototype = new Vehicle();

console.log( new Car() );
/**This will log a car object with the name hummer, the type car and the speed of 50mph **/