[英]typescript: member variables from super class's constructor
The following code will alert undefined
以下代码将警告
undefined
class Parent {
field: string
constructor() {
alert(this.field)
}
}
class Child extends Parent {
field = 'child'
}
new Child() #=> undefined
whereas, the following alerts 'child' as expected 但是,以下警报按预期发出“孩子”警报
class Parent {
field: string
constructor() {
alert(this.field)
}
}
class Child extends Parent {
field = 'child'
constructor() {
// without referencing this.field before super(), this.field stays undefiend
this.field
super()
}
}
new Child() #=> 'child'
Is there any ways to accomplish the following conditions? 有什么方法可以满足以下条件?
What jumps to mind is: 突然想到的是:
class Parent {
constructor(public field: string) {
alert(this.field)
}
}
class Child extends Parent {
constructor() {
super('child');
}
}
new Child() #=> 'child'
This doesn't meet your conditions but I feel it is fairly compact. 这不符合您的条件,但我觉得它非常紧凑。
Well you could defer the property access to a micortask: 好吧,您可以将属性访问权限推迟到micortask:
class Parent {
field: string
constructor() {
Promise.resolve().then(() => {
alert(this.field)
};
}
}
But while that fullfills your conditions, it is ... still the wrong approach. 但是,尽管可以满足您的条件,但这仍然是错误的方法。 Pass
field
as a constructor argument, as other answers show. 如其他答案所示,将
field
作为构造函数参数传递。
There's no way to accomplish your conditions, i'm pretty sure. 我很确定,没有办法完成您的条件。
Grabbing the member variable in sub class happens after the base class constructor runs, and calling super()
must be the first statement in a sub class constructor. 在基类构造函数运行之后,将发生子类成员变量的获取,并且调用
super()
必须是子类构造函数中的第一条语句。
class Child extends Parent {
field = 'child';
}
// the above is equal to:
class Child extends Parent {
constructor(){ super(); this.field = 'child'; }
}
And this would cause error: 这会导致错误:
class Child extends Parent {
constructor(){
this.field = 'child'; // ERROR!
super();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.