【发布时间】:2019-01-01 21:42:34
【问题描述】:
我试图找出当前派生类是否有属性设置器。原因是我通过扩展类的构造函数循环了几个选项。并且只想分配那些属于此类而不是基类的属性。
所以我需要一种可能性来找出这个类是否存在 getter 或 setter。我删除了尽可能多的代码以仅显示问题。
这是基类:
class baseClass{
constructor(wOptions){
//do some stuff
if(typeof wOptions == "object"){
for(let prop in wOptions){
// if(Object.getOwnPropertyDescriptor(this, prop) != undefined){
// if(this.hasOwnProperty(prop) != undefined){ /* doesn't work either */
if(typeof this[prop] != "undefined"){ /* calls the getter, if exists. */
this[prop] = wOptions[prop];
delete wOptions[prop];
}
}
}
}
get mainProperty(){
return 42;
}
set mainProperty(newValue){
return 42;
}
}
这是派生类:
class derivatedClass extends baseClass{
constructor(wOptions){
super(wOptions)
//do some other stuff
let html = document.body;
Object.defineProperty(this, "html", {value: html, writable: false});
if(typeof wOptions == "object"){
for(let prop in wOptions){
// if(Object.getOwnPropertyDescriptor(this, prop) != undefined){
// if(this.hasOwnProperty(prop) != undefined){ /* doesn't work either */
if(typeof this[prop] != "undefined"){ /* calls the getter, if exists. */
this[prop] = wOptions[prop];
delete wOptions[prop];
}
}
}
}
get otherProperty(){
return html.innerText;
}
set otherProperty(newValue){
return html.innerText = newValue;
}
}
以及如何初始化对象:
let options = {otherProperty: "new Text"};
let object = new derivatedClass(options);
console.log(options);
关于已经尝试过的解决方案:
-
getOwnPropertyDescriptor总是返回undefined;返回分配的options -
hasOwnProperty总是返回false;返回分配的options -
typeof this[prop] != "undefined"调用 getter,这可能很糟糕,因为 html 尚未定义。html.innerText的引用错误 - 不是解决方案,而是用于验证:删除派生类中的
if子句,将正文文本更改为new Text并在控制台中打印一个空对象。
在 Chrome 71 中测试。
有一些选项可以避免这种情况:
- 将此类处理的所有属性转移到另一个对象(非常丑陋且极有可能忘记列表中的属性)
- 始终使用
Object.defineProperty,因为它们将在super调用之后执行。但是,它并没有类构造的 get/set 函数那么漂亮。
是否有可能找出是否有可用于otherProperty 的设置器,它在派生类中评估为真,但在基类中不存在?
【问题讨论】:
标签: javascript class properties getter-setter exists