Constructors create instances of objects. Prototypes define shared methods and properties. Shared methods save memory, making prototypes ideal for creating objects.

It is very efficient to combine both methods, with using prototypes to share the methods reference and constructors to create instance properties. Properties of each object can be accessed using this keyword.

Example showing combination of constructors and prototypes

Here, the section instance property is added in constructor and methods are defined inside the Library.prototype. Hence, constructor can be called to create objects and access variables, with methods sharing the references to all objects created. 

The “bookHouse” and “myLib“ call methods from same reference, but have a copy of it’s own instance variables.

Since the constructor property points to the prototype, when it is changed to object literal notation, constructor points to Object, i.e.:

bookHouse.constructor === Library is false

bookHouse.constructor === Object is true

Hence after the prototype is over-written, constructor is again pointed to the right value, in constructor : Library.

 

›› go to examples ››