2017-08-23 44 views
2

給定以下類的層次結構:ChildClass extends ParentClass,是否可以從ParentClass構造函數中訪問ChildClass構造函數?例如:從基類構造函數訪問子構造函數

class ChildClass extends ParentClass 
{ 
    constructor() 
    { 
     super() 
    } 
} 

ChildClass.prop = 'prop' 

class ParentClass 
{ 
    constructor() 
    { 
     if (this._child().prop == 'prop') // here 
     { 
      console.log("All ok"); 
     } 
    } 

    get _child() 
    { 
     return this.constructor; 
    } 
} 

換句話說,我想要做的是進入孩子的「靜態」屬性進行覈查的目的

回答

5

,纔有可能從父類訪問ChildClass的構造函數構造函數?

每個孩子都是父母,但不是每個父母都是孩子。

不可以。即使可能有一些髒碼,也不要這樣做。重新考慮你的設計。在繼承鏈中,每個孩子都應該繼承父母的屬性。不是相反的。

想想看,有3個孩子,你得到了哪些孩子的道具?遊民。

+0

是的,這是可能的。不,「this.constructor」不是「髒代碼」,而是一種常用的方法來達到靜態屬性。如果這是一個設計錯誤,這取決於情況。 – estus

2

應該this._child代替this._child(),因爲child是屬性訪問,而不是一個方法:

class ParentClass 
{ 
    constructor() 
    { 
     if (this._child.prop == 'prop') 
     { 
      console.log("All ok"); 
     } 
    } 

    get _child() 
    { 
     return this.constructor; 
    } 
} 

_child吸氣是多餘的和誤導性的。通常this.constructor直接使用:

class ParentClass 
{ 
    constructor() 
    { 
     if (this.constructor.prop == 'prop') 
     { 
      console.log("All ok"); 
     } 
    } 
} 

在父類參考「孩子」是語義上不正確(家長不能也不應該「知道」關於它的孩子,_child可以是父母本身),但是指的是this不是。