javascript - 从派生类访问属性
问题描述
abstract class Base {
constructor() {
console.log(this.components)
}
components = ['']
}
class Child extends Base {
components = ['button', 'text']
}
const f = new Child()
运行这段代码,我得到
['']
但我宁愿得到
['button', 'text']
从派生类。 我想这样做的原因: 我想验证用户在 Child.xml 中定义的“组件”属性。不可能吗?
解决方案
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()
推荐阅读
- php - 如何将多个表的foreach限制为一个表
- java - 空指针异常,在控制器类中为 Oauth 编写 Junit/Mockito 测试用例时,JSON 响应
- scheme - 使用 Lilypond 音乐替换功能传递和返回音乐
- java - 空指针异常 Kotlin 应用程序
- mongodb - 可以在 <1 秒内通过 SQL 运行此查询,但聚合 MongoDB 不能在 45 分钟内从具有相同索引的同一数据集运行
- bash - 在 bash 命令行工具中将字符串或数组转换为单独的输入
- firebase - Firestore 中授权写入的安全规则
- spring - Spring Boot 的 spring-boot:run 不遵守指定的配置文件
- javascript - 在Javascript中按降序对字符串进行排序(最有效)?
- javascript - 即使在父状态更新后,子无状态功能组件也不会更新