TypeScript问题:无法通过Object.keys()访问子类属性
问题:子类属性无法在基类构造函数中被遍历
我希望将基类构造函数中定义的逻辑复用至所有子类,具体来说,想在构造函数中遍历类的所有属性。原本预期在基类构造函数中调用Object.keys(),同时子类构造函数调用super()就能实现该功能,但实际结果不符合预期。
代码示例
class BaseClass { private baseField1: string; private baseField2: string; constructor(data: any) { console.log(this.constructor.name + " has fields: " + Object.keys(this)); } } class ChildClass extends BaseClass { private childField1: string; constructor(data: any) { super(data); } } let base = new ChildClass({name: 'Joe'});
预期输出
ChildClass has fields: baseField1,baseField2,childField1
实际输出
ChildClass has fields: baseField1,baseField2
输出中并未包含childField1属性,请问该如何解决这个问题?
解决方法(更新)
最终实现了预期效果,感谢Touffy!
class BaseClass { private baseField1: string; private baseField2: string; constructor(data: any) { Object.assign(this, data); } } class ChildClass extends BaseClass { private childField1: string; constructor(data: any) { super(data); if (data.childField1) this.childField1 = data.childField1; } } let base = new ChildClass({ baseField1: 'bf1', baseFileds2: 'bf2', childField1: 'Joe' }); console.log('Class fields: ' + JSON.stringify(base));
输出结果
Class fields: {"baseField1":"bf1","baseFileds2":"bf2","childField1":"Joe"}
内容的提问来源于stack exchange,提问作者Sergei
相关产品推荐
相关产品推荐

