【发布时间】:2020-01-31 06:07:59
【问题描述】:
我有一个子类 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]
}
}
}
}
我在第一个例子中做错了什么吗?
提前致谢。
【问题讨论】:
-
JavaScript 允许各种疯狂的事情,因为它是动态的,但是从基类访问子类会完全破坏 OO
标签: node.js typescript inheritance