Reputation: 145
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
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
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