typescript - Value not yet initialized in parent class when calling method from base class
问题描述
We have the following structure
abstract class testParent{
constructor(){
console.log(this.doSomething());
}
abstract doSomething():string;
}
class testChild extends testParent{
private x:string = 'someValue';
constructor(){
super();
}
doSomething():string{
return this.x;
}
}
const y = new testChild();
And we noticed that the string x is not yet initialized so it returns undefined. But we would like to have this structure. What are some ways to deal with this problem?
We thought of one solution
abstract class testParent{
constructor(){
this.initialize();
console.log(this.doSomething());
}
abstract initialize():void;
abstract doSomething():string;
}
class testChild extends testParent{
private x:string = '';
initialize():void{
this.x = 'someValue';
}
doSomething():string{
return this.x;
}
}
const y = new testChild();
But this feels quite hacky.
解决方案
The problem is that you're trying to access x
before it is initialized.
Even though you're probably not aware, in reality your constructor does this:
constructor() {
super();
this.x = 'someValue';
}
which means doSomething()
is called with this.x
not yet being assigned a value.
Same thing happens if you omit the constructor entirely
constructor() {
super(...arguments);
this.x = '';
}
You can check that this is happening if you for example debug this on the playground:
You'll have to additionally open the console (F12) to enable the breakpoint being hit
I think the most accurate solution is the one you already presented, basically your parent needs to initialise the property before calling super()
推荐阅读
- memory - 存储和加载 2d 无限程序生成的基于瓦片的世界
- ansible - Ansible / Jinja2 获取项目文件管理器
- node.js - Dialogflow 和 heroku Webhook
- graphics - NAudio 2 通道波形到图形
- python - 在 for 循环中选择组合?
- angular - Angular-CDK SVG 没有出现
- php - Wordpress Duplicator 插件使用 XAMPP 失败“必需路径”
- r - 如何在 ggplot 中连接点 - 2 个单独的 geom_point 函数
- python - 如何在python中输入逗号分隔的正整数对,每对用分号(;)分隔
- solr - 在 Datastax Solr 中创建的 Banana 中加载多个内核