从基类构造函数访问子构造函数



给定以下类层次结构:ChildClass扩展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;
}
}

换句话说,我正在尝试做的是访问孩子的"静态"属性以进行验证

是否可以从ParentClass构造函数访问ChildClass构造函数?

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

不。你不能。即使可能使用一些肮脏的代码,也不要这样做。重新思考您的设计。在继承链中,每个子项都应继承父项的属性。反之则不然。

试想一下,有3个孩子,你得到哪些儿童道具?无赖。

它应该是this._child而不是this._child(),因为child是属性访问器,而不是方法:

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

_childgetter是多余的和误导性的。通常this.constructor直接使用:

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

在父类中引用"子"在语义上是不正确的(父级没有也不应该"知道"其子级,_child本身可以是父级(,但引用this则不是。

最新更新