Why does newtoy.constructor === Gadget result in console false?
怪我咯
怪我咯 2017-06-26 10:57:07
0
2
901
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

The above example is taken from the book "Object-Oriented Programming Guide"

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
学霸

If the code is written correctly, it is false, because you have rewritten the prototype object of Gadget, and the prototype object you rewritten does not have a constructor attribute. You can refer to Chapter 6 of "JavaScript Advanced Programming" Introduction to prototype

typecho

The correct answer upstairs, Gadget.prototype has been rewritten. Because there is an implicit constructor in the prototype object, which points to the constructor itself. As follows:

Prototype expansion is best written in this form:

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

Or use Object.assign() to merge objects:

Test.prototype = Object.assign(Test.prototype, {
    newAttr: '',
    newFn: function() {
        ...
    }
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template