Magic Lasso
Magic Lasso

Reputation: 1542

Javascript defineProperty

When using:

Object.defineProperty(obj,prop,desc){
    get: function(){...
    set: function(){...
}

Does the getter/setter apply to obj[prop] or does it act on obj no matter what property is specified?

I am asking because I'm trying to setup some data binding based on a nested object like:

obj[propA] = {propB:'seomthing',propC:'somethingElse'}

and when I do something like this:

var obj = {value:{propA:'testA',propB:'testB'}};

Object.defineProperty(obj.value,'propA',{
    get: function(){return this.value;},
    set: function(newValue){this.value=newValue;console.log('propA: ',newValue);}
});

console.log(obj.value.propA);

obj.value.propA = 'testA';

Object.defineProperty(obj.value,'propB',{
    get: function(){return this.value;},
    set: function(newValue){this.value=newValue;console.log('propB: ',newValue);}
});

console.log(obj.value.propB);

obj.value.propB = 'testB';

console.log('propA: ',obj.value.propA,' --propB: ',obj.value.propB);

the getter assigns the value to ALL the properties set by defineProperty within the object.

If this is the correct functionality, is there a way to have the getter/setter work only on the property defined such that in the fiddle above, propA would yield testA and propB would yield testB?

Upvotes: 0

Views: 175

Answers (1)

Ry-
Ry-

Reputation: 224913

The getter and setter only apply to the named property, but this inside each one refers to the object whose property it is (you don’t have to have a backing variable for every property).

In your example, you’re always reading and modifying obj.value.value. You can create a different variable for each one by wrapping each in an IIFE, for example:

(function () {
    var value;

    Object.defineProperty(obj.value, 'propA', {
        get: function () { return value; },
        set: function (newValue) { value = newValue; },
    });
})();

Updated fiddle

Upvotes: 4

Related Questions