Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  156] [ 1]  / answers: 1 / hits: 20733  / 13 Years ago, sat, october 8, 2011, 12:00:00

I have an object containing both public and private variables. The public variables are assigned to the private variables (I think), however, whenever I modify the private variables with a function, the public variables don't update.



var foo = (function() {
//Private vars
var a = 1;

return {
//Public vars/methods
a: a,
changeVar: function () {
a = 2;
}
}
})();
alert(foo.a); //result: 1
foo.changeVar();
alert(foo.a); //result: 1, I want it to be 2 though


Now I know that if I change the line in changeVar to this.a = 2; it works but then it doesn't update the private variable. I want to update both the private and public variables at the same time. Is this possible?



JsFiddle showing problem


More From » variables

 Answers
9

When you set the a key in the object you're returning, that's making a copy of the 'private' a variable.



You can either use a getter function:



return {
//Public vars/methods
a: function() { return a; },
changeVar: function () {
a = 2;
}
};


Or you can use Javascript's built-in accessor functionality:



obj = {
//Public vars/methods
changeVar: function () {
a = 2;
}
};
Object.defineProperty(obj, a, { get: function() { return a; } });
return obj;

[#89732] Thursday, October 6, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriechantalr

Total Points: 380
Total Questions: 95
Total Answers: 86

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
;