node.js - 打字稿:从基类设置器访问子类的属性
问题描述
我有一个子类 Employee 和一个基类 Person。在 Person 类的构造函数中,我调用了 setter 函数,该函数在一些验证后设置属性。但是在 setter 函数中,我无法获取 Employee Class 的属性。
//Employee.ts
import Person from "./Person"
class Employee extends Person {
empID: string = '';
designation: string = '';
constructor (props) {
super(props);
}
}
let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee(obj)
//Person.ts
export default class Person {
firstName: string = '';
lastName: string = '';
constructor (props:object) {
this.props = props
}
set props(props:object) {
console.log("this",this)
/***************prints Employee { firstName: '', lastName: '' } cannot access empID and designation **********/
for (const f in props) {
if (this.hasOwnProperty(f)) {
this[f] = props[f]
}
}
}
}
但这有效
//Employee.ts
import Person from "./Person"
class Employee extends Person {
empID: string = '';
designation: string = '';
constructor () {
super();
}
}
let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee()
employee.props = obj
//Person.ts
export default class Person {
firstName: string = '';
lastName: string = '';
constructor () {
}
set props(props:object) {
console.log("this",this)
/***************prints Employee { firstName: '', lastName: '', empID: '', designation: '' } **********/
for (const f in props) {
if (this.hasOwnProperty(f)) {
this[f] = props[f]
}
}
}
}
我在第一个例子中做错了什么。
提前致谢。
解决方案
推荐阅读
- python - 提高循环数学脚本的效率
- apache-kafka - Kafka 在尝试访问磁盘上的日志文件时抛出异常磁盘错误
- php - 如何从模态html中的输入中获取数据?
- ios - 如何处理对 UI 来说太快的更新?
- c# - 获取在 DataGridView 中签入的选定学生
- python - 这个日志记录在哪里?
- objective-c - NSApplication -runModalSession 崩溃
- python - 如何在不在命令行中写入类名的情况下调用类方法
- c# - 如何更新现有的 itemCode
- swift - CollectionView cellForItemAt 从不运行