wackozacko
wackozacko

Reputation: 702

Javascript getters and setters for object, not object properties

I know how to use JS getters and setters for object properties like so

var myObject = {
    value : 0,
    get property() {
        return this.value;
    },
    set property(v) {
        this.value = v;
    }
}

so that calling myObject.property = 2 will set myObject.value, but what I'm wondering is if there is some way to call myObject = 2 and still set myObject.value rather than changing myObject from an object into a number.

It's probably not possible, but javascript is an incredibly flexible language and I thought I'd pose the question to the community before I discarded the idea.

Upvotes: 6

Views: 4693

Answers (2)

Zach Smith
Zach Smith

Reputation: 8961

Just as a side note. I didn't know until reading this question that you could define getters/setters without Object.defineProperty. I was wondering at what the difference was between this 'shorthand' method, and defining getters/setters via Object.defineProperty.

I found, using the myObject example in the question:

var myObject = {
    value : 0,
    get property() {
        return this.value;
    },
    set property(v) {
        this.value = v;
    }
}

that Object.getOwnPropertyDescriptor(myObject, 'property')

returns

get: ƒ property()
set: ƒ property(v)
enumerable: true
configurable: true

So worth mentioning is that property in this case is enumerable, meaning it will show up in loops.

Upvotes: 1

Siddharth
Siddharth

Reputation: 1166

It is possible indeed. Only for global variables though.

Object.defineProperties(this, {
    myObject: {
        get: function () {
            return myObjectValue;
        },
        set: function (value) {
            myObjectValue = value;
        },
        enumerable: true,
        configurable: true
    },
    myObjectValue: {
        value: 0,
        enumerable: false,
        configurable: true,
        writable: true
    }
});

myObject = 5;
console.log(myObject);
console.log(delete myObject);

Now, every time you assign a value to myObject, it shall actually run the set function and assign the value to the other property instead. Now, if you wanted to minimize pollution, you could create an IIFE and use variables inside that instead to hold the values, per se.

http://jsbin.com/zopefuvi/1/edit

And here is the version with the IIFE.

http://jsbin.com/puzopawa/1/edit

Upvotes: 3

Related Questions