In JavaScript Prototype inheritance, what is the goal of adding prototype.constructor property. Let me explain with an example.
var Super = function() { this.superProperty = 'Super Property' } var Sub = function() { this.subProperty = 'Sub Property' } Sub.prototype = new Super(); Sub.prototype.constructor = Sub; // advantages of the statement var inst = new Sub();
The following lines return always true in all case, when adding Sub.prototype.constructor = Sub or not.
console.log(inst instanceof Sub) // true console.log(inst instanceof Super) // true
I guess, it may be useful when getting new instances but when and/or how?
Thanks in advance.
Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.
constructor. The constructor property returns a reference to the Object constructor function that created the instance object. Note that the value of this property is a reference to the function itself, not a string containing the function's name. Note: This is a property of JavaScript objects.
So what's the difference between constructor and prototype? A short answer is that the constructor is a function that is used to create an object, while the prototype is an object that contains properties and methods that are inherited by objects created from a constructor.
prototype. A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description.
It's just to properly reset the constructor
property to accurately reflect the function used to construct the object.
Sub.prototype = new Super();
console.log(new Sub().constructor == Sub);
// -> 'false'
Sub.prototype.constructor = Sub;
console.log(new Sub().constructor == Sub);
// -> 'true'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With