Home  >  Q&A  >  body text

Why does newtoy.constructor === Gadget result in console false?

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"

怪我咯怪我咯2646 days ago832

reply all(2)I'll reply

  • 欧阳克

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

    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

    reply
    0
  • typecho

    typecho2017-06-26 10:59:07

    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() {
            ...
        }
    })

    reply
    0
  • Cancelreply