gpt4 book ai didi

javascript - 确定属性(property)是来自 parent 还是 child

转载 作者:搜寻专家 更新时间:2023-10-30 21:14:47 26 4
gpt4 key购买 nike

我想在子类中编写一个简单的函数,返回它自己的键(而不是父类)。

class Parent{
protected _parentAttribute!: string;
constructor() {
this._parentAttribute='test';
}
}

class Child extends Parent{
childAttribute!: string;
constructor() {
super();
console.log("My unique child keys are:", Object.keys(this));
}
}
let child=new Child();

结果:我唯一的子键是:[_parentAttribute,childAttribute]

期望的结果:我唯一的子键是:[childAttribute]

这可能吗?

最佳答案

首先,在顶级类中创建一个变量,然后在该变量中存储顶级类中的键。在子类中使用过滤函数来过滤顶级变量。我认为这种方法没有什么不好。过滤器应该可以正常工作,并且此方法应该每次都有效。

class Parent{
protected _parentAttribute: string;
protected topKeys;
constructor() {
this._parentAttribute='test';
this.topKeys = 'test' // asign something it so it comes in your property names
let somevar = Object.getOwnPropertyNames(this) // get all the properties
this.topKeys = somevar // put them in this variable
}

}
class Child extends Parent{
public childAttribute: string;
constructor() {
super();
this.childAttribute = 'test'
let keyofChild = Object.keys(this).filter(keys => !this.topKeys.includes(keys))
console.log("My unique child keys are:", keyofChild); // childAttribute
}
}

let child = new Child();

关于javascript - 确定属性(property)是来自 parent 还是 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com