首页 > 解决方案 > 打字稿:从基类设置器访问子类的属性

问题描述

我有一个子类 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]
            }
        }
    }
}

我在第一个例子中做错了什么。

提前致谢。

标签: node.jstypescriptinheritance

解决方案


当您调用super子类时尚未初始化。您可以propssuper通话后立即设置:

constructor (props) {
    super();
    this.props = props;
}

操场


推荐阅读