Typescript: доступ к свойствам подкласса из установщика базового класса - PullRequest
0 голосов
/ 31 января 2020

У меня есть подкласс Employee и базовый класс Person. В конструкторе класса Person я вызываю функцию setter, которая устанавливает атрибуты после некоторой проверки. Но в функции setter я не могу получить свойства класса Employee.

//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]
            }
        }
    }
}

Я что-то не так делаю в первом примере.

Заранее спасибо.

1 Ответ

1 голос
/ 31 января 2020

При вызове super подкласс еще не инициализирован. Вы можете установить props сразу после super вызова:

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

Детская площадка

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...