简体   繁体   中英

Setter/getter for class property (Object.assign)?

I'm trying to be trigger a setter on a class property:

class Example {
    prop = { default: 'default', color: 'red' };

    set prop(value) {
        // this.prop will be undefined as the setter overrides the class property)
        Object.assign(this.prop, value);
    }
}

const myExample = Example();
myExample.prop.default = 'new';

// Trying to get prop = { default: 'new', color: 'red' }

The setter will override prop I believe, how could I specify a default object value? Should I store the class property prop as like _prop?

I would define the accessors manually in the constructor:

 class Example { constructor() { var prop = { default: 'default', color: 'red' }; Object.defineProperty(this, 'prop', { get() { return prop; }, set(value) { Object.assign(prop, value); } }); } } const myExample = new Example(); console.log(myExample.prop); myExample.prop = {foo: "bar"}; console.log(myExample.prop); 

If you don't mind prop being public, you could move the accessors outside the constructor, and share them among all instances:

 class Example { constructor() { this._prop = { default: 'default', color: 'red' }; } get prop() { return this._prop; } set prop(value) { Object.assign(this._prop, value); } } const myExample = new Example(); console.log(myExample.prop); myExample.prop = {foo: "bar"}; console.log(myExample.prop); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM