【问题标题】:JavaScript prototype overridingJavaScript 原型覆盖
【发布时间】:2021-01-26 02:48:53
【问题描述】:

我是学习 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();

在调用 cat1.printName() 时,我希望它会记录“猫原型中的猫”,但它会记录“动物原型中的猫”。有人可以向我解释原因。谢谢。

【问题讨论】:

    标签: javascript prototype


    【解决方案1】:

    您是对的,但是当您重置 Cat.prototype 时,您对 printName() 函数的覆盖本身会被下一行覆盖。只需移动代码的顺序即可解决问题:

    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"

    【讨论】:

    • 非常感谢您的解释。
    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 2011-02-06
    相关资源
    最近更新 更多