Aziule
Aziule

Reputation: 441

defineProperty on nested class object

Let's say we have this class:

var MyClass = function() {
    this.oneProp = 'one prop';
    this.myProps = {
        prop1: 'my prop1',
        prop2: 'my prop2'
    };
});

How can I configure a getter / setter on myProps.prop1 using Object.defineProperty so that when I change myProps.prop1, the value of myProps.prop2 is set to, for example, '_'+prop1?

I found an easy way to define a getter / setter on oneProp using:

Object.defineProperty(MyClass.prototype, 'oneProp', {
    ...
});

But I can't figure out how to do the same on myProps.prop1.

Thanks

Upvotes: 3

Views: 1022

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386520

You can write the getter directly in the object literal.

var MyClass = function() {
    this.oneProp = 'one prop';
    this.myProps = {
        prop1: 'my prop1',
        get prop2() { return '_' + this.prop1; },
        set prop2(v) { this.prop1 = v; }
    };
}

var x = new MyClass;
document.write(x.myProps.prop2 + '<br>');
x.myProps.prop2 = 42;
document.write(x.myProps.prop2 + '<br>');

Upvotes: 4

Related Questions