Heim  >  Fragen und Antworten  >  Hauptteil

Warum führt newtoy.constructor === Gadget dazu, dass die Konsole falsch ist?

function Gadget(name,color){
    this.name=name;
    this.color=color;
    this.whatAreYou=function(){
        return 'I am a ' + this.color + ' ' + this.name;
    };
}

Gadget.prototype={
    price:100,
    rating:3,
    getInfo:function(){
        return 'Rating: ' + this.rating + ', price: ' + this.price;
    }
};

var newtoy=new Gadget('webcam','black');
new.rating;//3
newtoy.constructor === Gadget;//true

Das obige Beispiel stammt aus dem Buch „Object-Oriented Programming Guide“

怪我咯怪我咯2646 Tage vor829

Antworte allen(2)Ich werde antworten

  • 欧阳克

    欧阳克2017-06-26 10:59:07

    如果代码没写错的话,那么就是false,因为你已经把Gadget的原型对象给重写了,而你重写的原型对象中没有constructor属性,可以参考一下《JavaScript高级程序设计》中第六章关于原型的介绍

    Antwort
    0
  • typecho

    typecho2017-06-26 10:59:07

    楼上正解,Gadget.prototype 被重写了。因为原型对象中有个隐式的constructor,指向了构造函数本身。如下:

    原型拓展,最好写成这种形式:

    Test.prototype.newFn = function() {
        ...
    }

    或者使用Object.assign()合并对象:

    Test.prototype = Object.assign(Test.prototype, {
        newAttr: '',
        newFn: function() {
            ...
        }
    })

    Antwort
    0
  • StornierenAntwort