gpt4 book ai didi

javascript - 实例化子类而不构造

转载 作者:行者123 更新时间:2023-12-01 00:43:52 25 4
gpt4 key购买 nike

我正在尝试使用 es6 类语法编写一个子类。在调用父类(super class)构造函数之前,子类需要执行一些复杂的逻辑,因此我尝试将其分解为函数。然而,这似乎是不可能的,因为 this 直到调用 super() 后才定义。

我尝试过简单地调用 super() 两次,一次在构造函数开始时,一次在结束时,但感觉不对,并且浪费了父类(super class)构造函数第一次所做的工作.

class Parent {
constructor(x) {
console.log('some expensive thing with ' + x);
}
}

class Child extends Parent {
constructor() {
let x = this.f();
super(x);
}

f() {
// complicated logic
return 3;
}
}

let c = new Child();

按照编写的方式运行代码会导致 ReferenceError: Must call super constructor in obliging before accessing 'this' or returned from returned constructor at new Child。删除 this 并尝试调用 f() 会导致 ReferenceError: f is not Define at new Child

是否有任何方法可以在其他地方分解子类构造函数逻辑,即使 this 未绑定(bind)也可以?

最佳答案

我将使用与构造函数分开的初始化函数,因为这可以让您更好地控制何时/是否发生父初始化。

class Parent {
constructor(x) {
this.init(x);
console.log("parent constructor does other stuff");
}
init(x) {
console.log("parent init runs")
}
}

class Child extends Parent {
constructor(x) {
super(x);
}

init(x) {
console.log("child init runs");
super.init(x); // This call is optional if you don't want to run the parent's init code
}
}

let c = new Child();

关于javascript - 实例化子类而不构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57535330/

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