从基类构造函数访问子构造函数
问题描述:
给定以下类的层次结构: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;
}
}
换句话说,我想要做的是进入孩子的“静态”属性进行核查的目的
答
,才有可能从父类访问ChildClass的构造函数构造函数?
每个孩子都是父母,但不是每个父母都是孩子。
不可以。即使可能有一些脏码,也不要这样做。重新考虑你的设计。在继承链中,每个孩子都应该继承父母的属性。不是相反的。
想想看,有3个孩子,你得到了哪些孩子的道具?游民。
答
应该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
不是。
是的,这是可能的。不,“this.constructor”不是“脏代码”,而是一种常用的方法来达到静态属性。如果这是一个设计错误,这取决于情况。 – estus