Javascript 在调用 super 之前初始化类属性

标签 javascript class subclass

我正在尝试将我的 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/

相关文章:

javascript - 为什么 Angular 子路由除了第一次之外不渲染组件?

javascript - 使用 Canvas 在三 Angular 形中画一个圆

javascript - jQuery 同位素过滤器没有项目?

c++ - 类定义和内存分配

java - 当父类(super class)不存在时调用父类(super class)的构造函数

ios - 子类化或不子类化 : that is the . ..?

Java SuperClass 和 SubClass 扩展可比较

javascript - 如何在 Angular2 中使用 <html> 模板?

c++ - 模板类中的通用模板指针

class - 使用 F# 在显式对象构造函数中失败