我尝试找出当前派生类是否具有属性设置器。原因是我通过扩展类的构造函数循环了几个选项。并且只想分配这些属性,这些属性是此类的一部分,而不是基类的一部分。

因此,我需要找出此类的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的设置器,该设置器在derivatedClass中评估为true,而在baseClass中评估为true?

最佳答案

试试这个

const descriptor = Object.getOwnPropertyDescriptor(derivatedClass.prototype, 'otherProperty');
console.log(descriptor);


如果derivatedClass.prototype有一个otherProperty(否则返回undefined),它将返回一个包含一些值的对象。在返回的对象中,您应该看到getset

More info here

07-25 21:56
查看更多