gpt4 book ai didi

JavaScript 原型(prototype)覆盖

转载 作者:数据小太阳 更新时间:2023-10-29 04:39:53 26 4
gpt4 key购买 nike

我刚开始学习 JavaScript 概念。想要了解原型(prototype)继承的工作原理。我的印象是,如果你的类继承了它的父类,并且你在两个类的原型(prototype)中有一个相同的命名方法,当你在子实例上调用该方法时,子原型(prototype)中的方法将被调用。

代码:

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() 时,我希望它记录“cat in cat prototype”,但它记录了“cat in Animal prototype”。有人可以向我解释原因吗?谢谢。

最佳答案

您是对的,但是当您重置 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"

关于JavaScript 原型(prototype)覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40917604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com