JSON stringify ES6 class property with getter/setter

后端 未结 5 1795
一向
一向 2020-11-30 13:40

I have a JavaScript ES6 class that has a property set with set and accessed with get functions. It is also a constructor parameter so the class can

5条回答
  •  粉色の甜心
    2020-11-30 14:05

    I made some adjustments to the script of Alon Bar. Below is a version of the script that works perfectly for me.

    toJSON() {
            const jsonObj = Object.assign({}, this);
            const proto = Object.getPrototypeOf(this);
            for (const key of Object.getOwnPropertyNames(proto)) {
                const desc = Object.getOwnPropertyDescriptor(proto, key);
                const hasGetter = desc && typeof desc.get === 'function';
                if (hasGetter) {
                    jsonObj[key] = this[key];
                }
            }
            return jsonObj;
        }
    

提交回复
热议问题