我正在尝试将我的 javascript 类从旧样式转换为新样式。问题是,新风格的 JavaScript 要求在访问 this
之前在构造函数中调用 super
。我必须扩展一个我不是其所有者的类,并且在该构造函数中它调用一个我在使用自己的属性时覆盖的方法。怎么解决?
class A {
constructor() {
this.create()
}
create() {}
reload() {
this.create()
}
}
class B extends A {
constructor(options) {
super()
this.options = options
}
create() {
let title = this.options.title // TypeError: Cannot read properties of undefined (reading 'title')
}
}
最佳答案
class A {
constructor(opts, arg) {
this.opts(opts);
console.log('prop in the parent constructor', this.p)
}
opts(opts){}
}
class B extends A {
constructor(opts, arg) {
super(opts, arg);
console.log('prop in the child constructor', this.p)
}
opts(opts){
console.log('before even constructor of class A called, this is called. Can be used to assign options')
Object.assign(this, opts)
}
}
let b = new B({
p: "my prop"
}, "some normal arg");
// you can also use it without any opts
console.log('---')
let c = new B({}, "some other arg");
这就是我喜欢为父类中所需的选项所做的事情
关于Javascript 在调用 super 之前初始化类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71186371/