gpt4 book ai didi

javascript - typescript :无法访问继承类构造函数中的成员值

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:09 25 4
gpt4 key购买 nike

我有一个类 A 和一个继承自它的类 B

class A {
constructor(){
this.init();
}
init(){}
}

class B extends A {
private myMember = {value:1};
constructor(){
super();
}
init(){
console.log(this.myMember.value);
}
}

const x = new B();

当我运行这段代码时,出现以下错误:

Uncaught TypeError: Cannot read property 'value' of undefined

我怎样才能避免这个错误?

我很清楚 JavaScript 代码会在创建 myMember 之前调用 init 方法,但应该有一些实践/模式才能使其工作。

最佳答案

这就是为什么在某些语言(咳嗽 C#)中,代码分析工具会标记构造函数中虚拟成员的使用。

在 Typescript 中,字段初始化发生在构造函数中,在调用基本构造函数之后。字段初始化写在字段附近的事实只是语法糖。如果我们查看生成的代码,问题就会变得很清楚:

function B() {
var _this = _super.call(this) || this; // base call here, field has not been set, init will be called
_this.myMember = { value: 1 }; // field init here
return _this;
}

您应该考虑一个解决方案,其中 init 从实异常(exception)部调用,而不是在构造函数中调用:

class A {
constructor(){
}
init(){}
}

class B extends A {
private myMember = {value:1};
constructor(){
super();
}
init(){
console.log(this.myMember.value);
}
}

const x = new B();
x.init();

或者您可以为您的构造函数添加一个额外参数,指定是否调用 init 并且不在派生类中调用它。

class A {
constructor()
constructor(doInit: boolean)
constructor(doInit?: boolean){
if(doInit || true)this.init();
}
init(){}
}

class B extends A {
private myMember = {value:1};
constructor()
constructor(doInit: boolean)
constructor(doInit?: boolean){
super(false);
if(doInit || true)this.init();
}
init(){
console.log(this.myMember.value);
}
}

const x = new B();

或者 setTimeout 的非常非常非常脏的解决方案,它将推迟初始化直到当前帧完成。这将使父构造函数调用完成,但是在构造函数调用和对象尚未被 inited

时超时到期之间会有一个过渡期
class A {
constructor(){
setTimeout(()=> this.init(), 1);
}
init(){}
}

class B extends A {
private myMember = {value:1};
constructor(){
super();
}
init(){
console.log(this.myMember.value);
}
}

const x = new B();
// x is not yet inited ! but will be soon

关于javascript - typescript :无法访问继承类构造函数中的成员值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49775508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com