gpt4 book ai didi

oop - typescript 父类正在调用派生函数

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

我有一个基类和一个派生类,每个都有初始化函数。

当我构建派生的时,我希望它:

  1. 调用它的基础构造函数:

    1.1。调用它的初始化函数

  2. 调用它自己的(派生的)初始化函数。

问题是派生的 init 函数被调用了两次。

代码:

class Base{
constructor() {
this.init();
}
init(){
console.log("Base init");
}
}
class Derived extends Base{
constructor() {
super();
this.init();
}
init(){
console.log("Derived init");
}
}
var obj = new Derived ();

输出:

Derived init
Derived init

最佳答案

万一,我们想调用基init(),然后调用子init(),我们可以这样解决:

constructor() {
super.init();
super();
}

检查 example here

先子后基的解决方案应该是这样的。

constructor() {
super();
//this.init();
super.init();
}

工作示例在 this playground 中.点击RUN可以看到生成了两个按钮

如果我们只想使用派生的东西,我们不必再次调用 init:

constructor() {
super();
//this.init();
// init will be called in super
}

此示例仅使用 child stuff

关于oop - typescript 父类正在调用派生函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28541586/

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