繁体   English   中英

为什么我的子类没有从 Javascript 中的父类继承属性?

[英]Why does my child class not inherit properties from the parent in Javascript?

我正在尝试了解 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

Dog.prototype.describe(this);

您正在使用Dog.prototype的调用上下文( this值)调用describe方法,并将 dog 实例作为第一个参数传递。 但是describe不接受任何参数,它试图从this获取属性。

Dog.prototype.describe.call(this); 相反,要使用 dog 实例的this值调用该方法:

 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.call(this); } var my_dog = new Schnauzer("Rupert"); my_dog.describe();

尽管如此,这还是有点难看,因为您必须使用.call来获取一个方法,在正常情况下,该方法在当前对象的原型链上会更高。 如果可能,您可以考虑重新命名您的Schnauzer.prototype.describe方法,这样它就不会掩盖Dog.prototype方法:

 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 = Object.create(Dog.prototype); Schnauzer.prototype.describeSchnauzer = function() { console.log(this.name + " is a Schnauzer with a shaggy beard"); this.describe(); } var my_dog = new Schnauzer("Rupert"); my_dog.describeSchnauzer();

或者使用class语法和super

 class Dog { legs = 4; arms = 0; describe() { console.log("Has " + this.legs + " legs and " + this.arms + " arms"); } } class Schnauzer extends Dog { constructor(name) { super(); this.name = name; } describe() { console.log(this.name + " is a Schnauzer with a shaggy beard"); super.describe(); } } var my_dog = new Schnauzer("Rupert"); my_dog.describe();

暂无
暂无

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

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