JavaScript/Constructors and prototypes

Constructor
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.

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

(The 'new' statement is the most common way to create a new JavaScript object from a constructor function, but a few JavaScript programmers sometimes use alternative techniques. )

Prototypes
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.

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

Dynamically extending objects
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.