最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Advantages of setting the "constructor" Property in the "prototype" - Stack Ove

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Feb 9, 2011 at 11:45 Fatih Acet asked Feb 9, 2011 at 11:31 Fatih AcetFatih Acet 29.6k9 gold badges53 silver badges58 bronze badges 1
  • See also Why is it necessary to set the prototype constructor? – Bergi Commented Jun 16, 2022 at 23:50
Add a ment  | 

1 Answer 1

Reset to default 10

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)

  1. 暂无评论