我是学习JavaScript概念的新手.想了解原型继承是如何工作的.我的印象是,如果您的类继承了它的父级,并且在两个类的原型中都有相同的命名方法,当您在子实例上调用该方法时,将调用子原型中的方法.
码:
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();
Run Code Online (Sandbox Code Playgroud)
在调用cat1.printName()时,我希望它能记录'cat in cat prototype',但它记录了'cat in Animal prototype'.有人可以向我解释一下原因.谢谢.