给出以下示例类结构:
class matter {
constructor(atomicNumber) {
this.atomicNumber = atomicNumber;
}
}
class stone extends matter {
constructor(atomicNumber, mohsHardness) {
super(atomicNumber);
this.mohsHardness = mohsHardness;
}
showProperties() {
console.log(Object.getOwnPropertyNames(this));
}
}
class gem extends stone {
constructor(atomicNumber, mohsHardness, carat) {
super(atomicNumber, mohsHardness);
this.carat = carat;
}
}
let chunk = new gem(6, 10, 1);
chunk.showProperties();
功能Object.getOwnPropertyNames
的输出符合预期,
['atomicNumber', 'mohsHardness', 'carat']
我将如何获得“父”类的属性,就像那样?
['atomicNumber', 'mohsHardness']
如果我替换这样的函数:
showProperties() {
const parentClass = Object.getPrototypeOf(Object.getPrototypeOf(this));
console.log(Object.getOwnPropertyNames(parentClass));
}
我得到结果
['constructor', 'showProperties']
这让我很茫然。也许与Object.prototype.hasOwnProperty相对应?
答案 0 :(得分:2)
问题在于,创建子实例时,this
和matter
构造函数中引用的stone
与对象中引用的this
完全相同。子构造函数(gem
)。子构造函数更改实例后,无法将子构造函数添加的属性与超级构造函数添加的属性区分开。
执行此类操作的唯一方法是在super
调用完成之后,在子构造函数更改对象之前检查对象:
class matter {
constructor(atomicNumber) {
this.atomicNumber = atomicNumber;
}
}
class stone extends matter {
constructor(atomicNumber, mohsHardness) {
super(atomicNumber);
this.mohsHardness = mohsHardness;
}
showProperties() {
console.log(this.parentProperties);
}
}
class gem extends stone {
constructor(atomicNumber, mohsHardness, carat) {
super(atomicNumber, mohsHardness);
this.parentProperties = Object.getOwnPropertyNames(this);
this.carat = carat;
}
}
let chunk = new gem(6, 10, 1);
chunk.showProperties();