2017-08-23 225 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不是。