【发布时间】:2020-01-20 05:36:03
【问题描述】:
我正在尝试了解 Javascript 的原型继承模型,但似乎缺少一些东西。我创建了以下一组对象:
function Dog() {
this.legs = 4;
this.arms = 0;
}
Dog.prototype.describe = function() {
console.log("Has " + this.legs + " legs and " + this.arms + " arms");
}
function Schnauzer(name) {
Dog.call(this);
this.name = name;
}
Schnauzer.prototype.describe = function() {
console.log(this.name + " is a Schnauzer with a shaggy beard");
Dog.prototype.describe(this);
}
var my_dog = new Schnauzer("Rupert");
my_dog.describe();
我的期望是这会输出:
Rupert is a Schnauzer with a shaggy beard
Has 4 legs and 0 arms
但这是我实际得到的:
Rupert is a Schnauzer with a shaggy beard
Has undefined legs and undefined arms
【问题讨论】:
-
是否需要在
Schnauzer中创建new Dog?您不应该为此使用class吗? -
您实际上并没有从
Dog继承Schnauzer。您需要设置Schnauzer.prototype = Object.create(Dog.prototype)并将构造函数属性添加回来:Schnauzer.prototype.constructor = Schnauzer:MDN: Inheritance in JavaScript
标签: javascript inheritance prototype