首页 > 解决方案 > 从派生类访问属性

问题描述

abstract class Base {
  constructor() {
    console.log(this.components)
  }
  components = ['']
}
class Child extends Base {
  components = ['button', 'text']
}

const f = new Child()

运行这段代码,我得到

[''] 

但我宁愿得到

['button', 'text']

从派生类。 我想这样做的原因: 我想验证用户在 Child.xml 中定义的“组件”属性。不可能吗?

标签: javascripttypescriptsubclass

解决方案


components 属性是在基类中的构造函数被调用之后设置的:

abstract class Base {
  constructor() {
    console.log(this.components)
  }

  components = ['']
}

class Child extends Base {
  constructor() {
    // inherited components from base = ['']
    super() // Call base constructor

    // this.components = ['button', 'text']
  }

  components = ['button', 'text']
}

const f = new Child()

您需要等待基本构造函数同步完成,然后才能访问新值 - 即。通过使用setTimeout

constructor() {
  setTimeout(() => console.log(this.components))
}

理想情况下,您应该将组件作为参数传递:

abstract class Base {
  constructor(public components = ['']) {
    console.log(components)
  }
}

class Child extends Base {
  constructor() {
    super(['button', 'text'])
    // this.components = ['button', 'text']
  }
}

const f = new Child()

推荐阅读