繁体   English   中英

从派生类访问属性

[英]Access properties from derived class

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

const f = new Child()

运行这段代码,我得到

[''] 

但我想得到

['button', 'text']

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

在调用基类中的构造函数之后,立即设置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()

尝试这个:

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

const f = new Child()

要么

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

}

const f = new Child(['button', 'text'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM