代码之家  ›  专栏  ›  技术社区  ›  einarmagnus

javascript对象模型:奇怪的构造函数属性

  •  4
  • einarmagnus  · 技术社区  · 14 年前

    我发现这段代码的行为令人费解,为什么 child Child ?有人能给我解释一下吗?

    function Parent() {
        this.prop1 = "value1";
        this.prop2 = "value2";
    }
    
    function Child() {
        this.prop1 = "value1b";
        this.prop3 = "value3";
    }
    Child.prototype = new Parent();
    
    var child = new Child();
    
    // this is expected
    console.log(child instanceof Child); //true
    console.log(child instanceof Parent); //true
    
    // what??
    console.log(child.constructor == Child); //false
    console.log(child.constructor == Parent); //true
    
    2 回复  |  直到 14 年前
        1
  •  5
  •   Community CDub    8 年前

    正如Pointy指出的那样, in his answer

    “constructor”属性是 对创建的函数的引用 对象的原型,而不是对象 本身。

    处理这个问题的通常方法是增加对象的原型 constructor 属性分配给 prototype

    function Parent() {
        this.prop1 = "value1";
        this.prop2 = "value2";
    }
    
    function Child() {
        this.prop1 = "value1b";
        this.prop3 = "value3";
    }
    Child.prototype = new Parent();
    
    // set the constructor to point to Child function
    Child.prototype.constructor = Child;
    
    var child = new Child();
    
    // this is expected
    console.log(child instanceof Child); //true
    console.log(child instanceof Parent); //true
    
    // corrected
    console.log(child.constructor == Child); // now true
    console.log(child.constructor == Parent); // now false
    
    console.log(Child.prototype.constructor); // Child
    console.log(Parent.prototype.constructor); // Parent
    

    我不能推荐斯托扬·斯特凡诺夫的 Object Oriented JavaScript 足够详细地介绍了原型和继承(如果可以的话,请参阅第二版,因为它解决了对第一版的一些批评)。

        2
  •  4
  •   Pointy    14 年前

    “constructor”属性是对创建对象的 原型 ,而不是对象本身。