简体   繁体   English

JavaScript 原型覆盖

[英]JavaScript prototype overriding

I am new at learning JavaScript concepts.我是学习 JavaScript 概念的新手。 Want to understand how prototypical inheritance work.想了解原型继承是如何工作的。 My impression was if your class inherits its parent, and you have a same named method in prototypes of both classes, when you call the method on child instance, the method in the child prototype will be called.我的印象是如果你的类继承了它的父类,并且你在两个类的原型中有一个相同的命名方法,当你在子实例上调用该方法时,将调用子原型中的方法。

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

On calling cat1.printName() I expected it to log 'cat in cat prototype' but it logged 'cat in Animal prototype'.在调用 cat1.printName() 时,我希望它记录“cat in cat prototype”,但它记录了“cat in Animal prototype”。 Could someone please explain the reason to me.有人可以向我解释原因。 Thanks.谢谢。

You are correct, but your override of the printName() function is, itself, being overridden by the next line when you reset the Cat.prototype .您是对的,但是当您重置Cat.prototype时,您对printName()函数的覆盖本身会被下一行覆盖。 Simply moving the order of the code fixes the issue:只需移动代码的顺序即可解决问题:

 function Animal(name) { this.name = name; } Animal.prototype.printName = function() { console.log(this.name + ' in animal prototype'); } function Cat(name) { Animal.call(this, name); } // OLD LOCATION of code // This was overriding your override! // Setting the prototype of an object to another object // is the basis for JavaScript's prototypical inhertiance // This line replaces the existing prototype object (which is // where your override was) with a completely new object. Cat.prototype = Object.create(Animal.prototype); // NEW LOCATION // AFTER setting the prototype (and creating inheritance), // it is safe to do the override: Cat.prototype.printName = function() { console.log(this.name + ' in cat prototype'); } var anm1 = new Animal('mr cupcake'); anm1.printName(); // "mr cupcake in animal prototype" var cat1 = new Cat('cat'); cat1.printName(); // "cat in cat prototype"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM