开发者

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

开发者 https://www.devze.com 2023-02-09 05:24 出处:网络
In JavaScript Prototype inheritance, what is the goal of adding prototype.constructor property. Let me explain with an example.

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() {开发者_StackOverflow
    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.


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' 
0

精彩评论

暂无评论...
验证码 换一张
取 消