If I have the following code that creates a copy of a prototype, does that really create a copy or just a reference back to Animal?
function Animal() { }
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
If I were to change .eat() in Bird’s copied prototype, will that change the .eat() function for Animal and all other objects that copied the Animal Prototype?
Does this also mean Bird is a sub-type to the supertype because of the copy?
You’ve already found your solution but for anyone interested (and also for the sake of my own learning, because I just researched it ), here’s how you can check this.
function Animal() { }
Animal.prototype.eat = function() {
console.log("nom nom nom");
};
function Bird() { }
Bird.prototype = Animal.prototype;
console.log(Bird.prototype === Animal.prototype) // true
// This means that they both are references to the same object, hence changing a property on one will show on the other
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
console.log(Bird.prototype === Animal.prototype) // false
// This means that they are different objects, although they may have the same properties, thus changing properties on one won't have an effect on the other.
// Funny thing is that if we had set Bird's constructor to Bird after setting Birds prototype to the same reference as Animals, Animal would had a Bird constructor.