Wierd behaviour of constructor property of an object

前端 未结 2 451
离开以前
离开以前 2021-01-26 06:37

In the following code, why is \'scotty.constructor\' set to \'Dog\' function ? How is the constructor property of an object set in general ? Is it set to the function that creat

相关标签:
2条回答
  • 2021-01-26 07:08
    Employee.prototype = Object.create(Person.prototype);
    Employee.prototype.constructor = Employee; //If you don't set Object.prototype.constructor to Employee, 
                                               //it will take prototype.constructor of Person (parent). 
                                               //To avoid that, we set the prototype.constructor to Employee (child).
    

    MDN Reference


    You need to set prototype's constructor to ShowDog manually again else it will see the parent constructor

    ShowDog.prototype = new Dog();
    ShowDog.prototype.constructor = ShowDog
    

    // Dog Constructor
    function Dog(name, breed, weight) {
      this.name = name;
      this.breed = breed;
      this.weight = weight;
    }
    
    
    // Dog Prototype
    Dog.prototype.species = 'Canine';
    
    Dog.prototype.bark = function() {
      if (this.weight > 25) {
        console.log(this.name + ' says Woof!');
      } else {
        console.log(this.name + ' says Yip!');
      }
    };
    
    Dog.prototype.run = function() {
      console.log('Run!');
    };
    
    // ShowDog Constructor
    function ShowDog(name, breed, weight, handler) {
      this.name = name;
      this.breed = breed;
      this.weight = weight;
      this.handler = handler;
    }
    
    // ShowDog Prototype
    ShowDog.prototype = new Dog();
    ShowDog.prototype.constructor = ShowDog
    
    ShowDog.prototype.league = 'Webville';
    
    ShowDog.prototype.stack = function() {
      console.log('Stack');
    };
    
    // ShowDog Instance
    var scotty = new ShowDog('Scotty', 'Scotish Terrier', 15, 'Cookie');
    console.log('Scotty\'s constructor is ' + scotty.constructor);

    0 讨论(0)
  • 2021-01-26 07:10

    Object don't have an own constructor property, it's taken from their protos. So, without this line:

    ShowDog.prototype = new Dog();
    

    the inheritance diagram would be

    Once you assign new Dog to the prototype (thus discarding its current value), the picture becomes:

    and the constructor value (Dog) is taken from scotty.__proto__.__proto__

    To make inheritance work as intended, you have to assign the constructor manually:

    ShowDog.prototype = new Dog()
    ShowDog.prototype.constructor = ShowDog
    

    which yields the following diagram:

    0 讨论(0)
提交回复
热议问题