The constructor property in prototype chain
The constructor
property could be very useful when the type of an variable needs to be identified. In constructing a class and its instance, or even establishing inheritance by using prototypes, constructor
deserves more attention because it can be changed by default or by you.
An instance never has a constructor
property unless it is manually given. When the constructor
of an instance is accessed, it is traced in the whole prototype chain.
If there is no any prototype chain manually attached to the function (class), the constructor
of an instance is the class itself.
However, if the function’ prototype
object is enriched, the instance’s constructor
is changed.
Now the prototype
of the class ‘Cat’ has been changed and points to an object literal ‘Animal’, so cat.constructor
-> Cat.prototype.constructor
-> Animal.constructor
-> Object
.
The code below justifies the above-mentioned reason.
Certainly, we can directly re-define the constructor property of the instance by:
Note that it doesn’t change Cat.prototype.constructor, which is due to the asymmetric reading and writing in prototypal inheritance.
Supplyment (June 15, 2013)
Another example to show that the constructor
property of an instance is searched throughout the prototype chains.