[英]How to properly subclass a subclass in JavaScript?
我以為我對如何正確地擴展JavaScript中的類有很好的了解,但是當擴展子類時,當我重寫方法並從子類中調用父方法時,我會陷入無限循環。 我做錯了,或者您不應該在JavaScript中以這種方式子類化。
有人可以幫我教育嗎?
var Grand = function() { this.test(); }; Grand.prototype.constructor = Grand; Grand.prototype.test = function() { console.log( "Grand!") }; var Parent = function() { this.supr.constructor.call( this ); }; Parent.prototype = Object.create( Grand.prototype ); Parent.prototype.constructor = Parent; Parent.prototype.supr = Grand.prototype; Parent.prototype.test = function() { this.supr.test.call( this ); console.log( "Parent!" ); }; var Child = function() { this.supr.constructor.call( this ); }; Child.prototype = Object.create( Parent.prototype ); Child.prototype.constructor = Child; Child.prototype.supr = Parent.prototype; Child.prototype.test = function() { this.supr.test.call( this ); console.log( "Child!" ); }; var g = new Grand(); // Outputs "Grand!" var p = new Parent(); // Outputs "Grand!" "Parent!" var c = new Child(); // Error: Endless Loop!
我希望控制台記錄“大!”,“父母!”,“孩子!”。 當實例化一個新的Child()時,卻得到了一個無限循環。
我來自ActionScript,因此在JavaScript中創建類仍然會使我感到有些困惑。 我在這里先向您的幫助表示感謝!
問題在於這段代碼:
var Parent = function() {
this.supr.constructor.call( this );
};
考慮以下代碼執行時會發生什么:
var c = new Child();
this
是變量c
,因此this.supr.constructor
將始終是這些代碼行中設置的父級構造函數:
Child.prototype.supr = Parent.prototype; // i.e. this.supr = Parent.prototype
Parent.prototype.constructor = Parent; // i.e. this.supr.constructor = Parent
因此,當Child的構造函數調用this.supr.constructor.call( this );
它執行Parent
函數,然后再次執行this.supr.constructor.call( this );
導致再次調用Parent
函數,從而導致無限循環。
一種解決方法是調用基類函數,如下所示:
var Child = function() {
Child.prototype.supr.constructor.call( this );
};
這篇文章中的更多細節
我建議切換到es6。 這種原型可能是一團糟,更難以追蹤。 但是,如果您在瀏覽器中需要此代碼,則應將代碼轉換為es5 whit babel或類似代碼。 在Node env中,只要您沒有最新版本,就可以使用它。 一些最新的瀏覽器也支持它
class Grand { constructor() { this.test() } test() { console.log( "Grand!") } } class Parent extends Grand { test() { super.test() console.log( "Parent!" ) } } class Child extends Parent { test() { super.test() console.log( "Child!" ) } } let g = new Grand(); // Outputs "Grand!" let p = new Parent(); // Outputs "Grand!" "Parent!" let c = new Child(); // Outputs "Grand!" "Parent! "child!"
它不僅更具可讀性,而且代碼更少,更易於理解
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.