JavaScript/Constructors and Prototypes

Previous: Object Oriented Programming Index Next: Inheritance

ConstructorEdit

The new operator creates a new object based on a constructor and a prototype.

The constructor is a function matching the name of the object, and, when called by the new operator, has the keyword this assigned to the newly created instance of the object. The constructor can then assign any initial variables as required.

function CoinObject()
{
    this.value = 0; 
}
slug = new CoinObject();  // Creates a "slug" - a valueless coin (slug.value = 0).

The constructor can accept parameters - however, it is not possible to overload the constructors by having multiple functions with a different number of parameters.

PrototypesEdit

A prototype for an object is the set of auto-created fields and methods. It cannot operate by itself, and relies on an existing constructor.

When the object is created, the fields initialized in the prototype are copied to the newly created object.

function CoinObject()
{
    this.value = 0; 
}
CoinObject.prototype.diameter = 1;
slug = new CoinObject();  // A valueless coin (slug.value = 0), with diameter of 1 (slug.diameter = 1)

Since the prototype of an object behaves as an object, you can use this to create inheritance.

Dynamically extending objectsEdit

Objects within JavaScript are fully dynamic, and fields within an object can instantly be created if they do not already exist. If, for example, you discover that you now need to keep track of the thickness in the coin example, you can simply add the new field to the prototype.

Changing the prototype of an object allows existing instances of the object to gain access to that change.

When a property value has been assigned on a new object, that property takes precedence over the prototype property from its ancestor. If you delete the property from the new object, the chain of inheritance takes you back to the property from the parent object.

To demonstrate, an Animal constructor is used to create an object, a dog called Spot. After that creation, the constructor has a gender property added to it. That gender property is also accessible from the object for Spot.

The gender property can be updated, and if the gender property is deleted from the dog object, it will retrieve the desired property from its ancestor instead, the Animal constructor.

function Animal (type, name) {
    this.type = type || 'No type';
    this.name = name  || 'No name';
}
var dog = new Animal('dog', 'Spot');
 
// Add gender to the Animal object
Animal.prototype.gender = 'unspecified';
// dog.gender is 'unspecified'
 
dog.gender = 'male';
// dog.gender is 'male';
 
delete(dog.gender);
// dog.gender is once again, 'unspecified'
Previous: Object Oriented Programming Index Next: Inheritance
Last modified on 7 August 2012, at 12:11