How are inherited Prototype Functions affected by change?

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?

Link to challange:

Nevermind: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/object-oriented-programming/override-inherited-methods

You’ve already found your solution but for anyone interested (and also for the sake of my own learning, because I just researched it :smile: ), 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.
1 Like

Thank you. I didn’t know the difference between the two methods of copying the prototype and why it was needed to use .create.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.