Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of setting the "constructor" Property in the "prototype"

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.

like image 325
Fatih Acet Avatar asked Feb 09 '11 11:02

Fatih Acet


People also ask

What are the advantages of prototype in JavaScript?

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.

What is constructor function prototype?

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.

What is the difference between constructor and prototype?

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.

What is prototype property?

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.


1 Answers

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' 
like image 117
Andy E Avatar answered Oct 20 '22 01:10

Andy E