Search code examples
javascriptgetter-setter

defining getters/setters in an object literal with a self-invoking function javascript


When defining an object literal its possible to use a self-invoking function so the function has access to private variables,

obj={
    value:(function(){
        var private;
        return function(v){
            return (private = v ?? private)
        }
    })()
};

But is it possible to do the same thing with a getter/setter in an object literal?

obj={
    get value(){
        return value;
    },
    set value(v) {
        value=v;
    }
};

Solution

  • [edit 2022] A pretty old answer.

    More actual: you can create a factory function. In the snippet the factory creates an object with (get and set) access (through the closure) to a private variable.

    const obj1 = objFactory(`Hello`);
    const obj2 = objFactory(`World`);
    console.log(`${obj1.privateThing} ${obj2.privateThing}`);
    obj1.privateThing = `Goodbye`;
    console.log(`${obj1.privateThing} ${obj2.privateThing}`);
    
    function objFactory(somethingPrivate) {
      return {
        get privateThing() { return somethingPrivate; },
        set privateThing(value) { somethingPrivate = value; }
      };
    }

    The old answer:

    Not really. You can also create an Immediately Invoked Function Expression (IIFE) for obj though:

    obj = function(){
      var privatething = 'hithere';
      
      return {
        get value() {
          return privatething;
        },
        set value(v) {
          privatething = v;
        }
      };
    }();
    obj.value; //=> 'hithere';
    obj.value = 'good morning to you too';
    obj.value; //=> 'good morning to you too'