Nishaant Sharma
Nishaant Sharma

Reputation: 145

Implement a single function to set and get the value of All Private Variable in JavaScript Closures

I have a function which has some variable since they are inside a function, they are local to function hence private. Now I may have many such variable, inorder to set a value and get the variable value from outside, I have to write set and get for every private variable. Is there anyway in javascript to have common function for getting and setting all private variable(PrivateOne and PrivateTwo).

        privateClosure = (function(){
        var PrivateOne;
        var PrivateTwo;
        setPrivate = function(VariableName,Value)
        {
        VariableName = Value;
        }
        getPrivate = function(VariableName)
        {
        return VariableName;
        }
        return{setPrivate,getPrivate};
        })();
        // I want to do something like this
        privateClosure.setPrivate(PrivateOne,10);
        privateClosure.getPrivate(PrivateOne);
        privateClosure.setPrivate(PrivateTwo,20);
        privateClosure.getPrivate(PrivateTwo);
        //Only one Function for all the private variable in closure.



    Is there anyway in javascript to have common function for getting and setting all private variable(PrivateOne and PrivateTwo).

Upvotes: 0

Views: 79

Answers (2)

Bergi
Bergi

Reputation: 664969

Sure there is: eval does everything you want1.

const privateVars = (function(){
    var privateOne;
    var privateTwo;
    return {
        setPrivate(variableName, value) {
            eval(`(v) => { ${variableName} = v; }`)(value);
        },
        getPrivate(variableName) {
            return eval(variableName);
        };
    }
 }());

1: …and is, of course, totally unreasonable. Don't use this.


However, if you want something for

getting and setting all private variables

I wonder why they are private at all and you don't just use an object with public properties.

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138437

You could closure a Map:

 var data = (function(){
   var lookup = new Map();

   return {
     get(v){
       return lookup.get(v);
      },
      set(a,v){
       return lookup.set(a,v);
      }
   }
 })();

So you can do:

 data.set("a",1);
 alert( data.get("a"));

Upvotes: 1

Related Questions