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
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);
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: