简体   繁体   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()

Running this code, I get 运行这段代码,我得到

[''] 

But I would rather like to get 但我想得到

['button', 'text']

from the derived Class. 从派生的类。 Reason I want to do this: I want to validate the "components"-property, which the user defined in the Child. 我想这样做的原因:我想验证用户在Child中定义的“组件”属性。 Is it not possible ? 不可能吗?

The components property is being set just after the constructor in the base class has been called: 在调用基类中的构造函数之后,立即设置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()

You need to wait for the base constructor to synchronously complete, before you can access the new values - ie. 您需要等待基本构造函数同步完成,然后才能访问新值-即。 by using setTimeout : 通过使用setTimeout

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

Ideally you should pass the components as parameters: 理想情况下,您应该将组件作为参数传递:

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()

try this: 尝试这个:

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

const f = new Child()

or 要么

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