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