In my last write up, we realized the beauty of the constructor property of an object. We discussed how easy the said property made it for us to create an object of the same type without having direct access to the function that creates the objects.
So, where does the constructor property come from anyway!
When you access oStudent.constructor, you get the access to the constructor function of oStudent. However, oStudent does not contain the constructor property. Take a look at the snapshot below:
As can be seen in the watch snapshot above, the object oStudent does not contain any property in the name of constructor. So where does it get this property from? Recall my post on prototypes, and you will realize that the property comes from the prototype of its constructor function. Assume that the constructor function of oStudent is Student, and so lets watch prototype of Student below:
Voila! there it is. The property constructor comes from the prototype of the constructor function (Student) that created our object oStudent. Now, we know where the constructor property comes from, when you do oStudent.constructor.
So, what does this have to do with constructor resetting?
Again if you go back to my discussion on prototypes, you will know that you could augment (add) properties to the prototype of a function. You could add any number of properties. However, at times you may also want to replace the prototype itself, with your own object. In that case, you will have replaced the default prototype of the function with your own function, as below:
The trouble with doing this is, you lose the constructor property that the default prototype had. See what our new prototype contains vs what the original prototype contained:
On the left we see that the original prototype contains the constrictor property, but on the right the new prototype that we set does not have it. So therefore any new objects created from the function Student will not get the constructor property. So you will not be able to make use of the constructor property of the object if you wanted to.
How do I ensure the constructor property is not lost?
When you replace the default prototype with your own object, make sure that your new prototype keeps the constructor property. Below is how you would do it:
Simple, right! but extremely useful. Look below, how our new prototype looks now:
There you go! Our prototype now has the necessary property 'constructor'. Now, all new instances of the function Student will have access to it.
Can you now guess the output of lines 16 and 25 below?
Give it a shot and find out!



















