[英]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.