【问题标题】:Advantages of setting the "constructor" Property in the "prototype"在“原型”中设置“构造函数”属性的好处
【发布时间】:2011-06-24 01:50:26
【问题描述】:

在JavaScript Prototype继承中,添加prototype.constructor属性的目的是什么。让我用一个例子来解释。

变种超级=函数(){ this.superProperty = '超级属性' } 变子 = 函数() { this.subProperty = '子属性' } Sub.prototype = new Super(); Sub.prototype.constructor = Sub; // 语句的优点 var inst = new Sub();

无论是否添加 Sub.prototype.constructor = Sub,以下行在所有情况下都返回 true。

console.log(inst instanceof Sub) // true console.log(inst instanceof Super) // true

我猜,它在获取新实例时可能很有用,但何时和/或如何?

提前致谢。

【问题讨论】:

    标签: javascript inheritance prototype constructor


    【解决方案1】:

    只是适当地重置constructor属性,以准确反映用于构造对象的函数。

    Sub.prototype = new Super();
    
    console.log(new Sub().constructor == Sub);
    // -> 'false' 
    
    Sub.prototype.constructor = Sub;
    console.log(new Sub().constructor == Sub);
    // -> 'true' 
    

    【讨论】:

    • 不设置的后果到底是什么?或者换句话说,什么时候 Sub.prototype.constructor 的值真正重要?它似乎根本不影响 Sub 实例的创建,afaics。这一定是那些“如此明显”的事情之一,以至于没有人真正直截了当地说出来,因此它躲过了我 :-)
    • @Yetanotherjosh:好吧,在 OP 代码的情况下,如果他忽略了那一行,那么 inst.constructor === Super,即使它是用 new Sub() 实例化的。如果您不关心该属性,这通常不会成为问题,但如果您与其他代码共享实例,那么在某些情况下您可能会造成混淆,包括 new inst.constructor() 实际上会导致 @ 的实例987654326@ 而不是Sub()(因此它会丢失Sub.prototype 独有的属性)。 tl;dr 这是一个很好的编程习惯
    猜你喜欢
    • 2014-01-05
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    相关资源
    最近更新 更多