I am new to learning JavaScript concepts. Want to understand how prototype inheritance works. My impression was that if your class inherits a parent and you have the same method in the prototypes of both classes, when you call the method on the child instance, the method in the child prototype will be called.
the code:
function Animal(name) { this.name = name; } Animal.prototype.printName = function () { console.log(this.name + ' in animal prototype'); } function Cat(name) { Animal.call(this, name); } Cat.prototype.printName = function () { console.log(this.name + ' in cat prototype'); } Cat.prototype = Object.create(Animal.prototype); var anm1 = new Animal('mr cupcake'); anm1.printName(); var cat1 = new Cat('cat'); cat1.printName();
When calling cat1.printName (), I expected him to run "cat in cat prototype", but he registered "cat in Animal prototype". Maybe someone will explain the reason to me. Thanks.
javascript prototype
shilpi
source share