Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 508
wackozacko Avatar asked Aug 07 '14 19:08

wackozacko


People also ask

How do you check if an object has a property or not?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you check if an object does not have a property in JavaScript?

hasOwnProperty() method Every JavaScript object has a special method object. hasOwnProperty('myProp') that returns a boolean indicating whether object has a property myProp . hero. hasOwnProperty('name') returns true because the property name exists in the object hero .

Can functions be properties of objects?

A function that is a property of an object is called its method. So, here we've got a method sayHi of the object user . Of course, we could use a pre-declared function as a method, like this: let user = { // ... }; // first, declare function sayHi() { alert("Hello!"); } // then add as a method user.


1 Answers

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

like image 164
Siddharth Avatar answered Oct 05 '22 10:10

Siddharth