Can someone explain why the private variable, _a, isn’t being updated with the setter? I must be missing something really obvious but can’t see it.
var f = function(a){
var _a = a;
return {
getA : _a,
setA : function(e){
_a = e;
}
}
};
var d = f(1);
console.log(d.getA); // 1
d.setA(2);
console.log(d.getA); // 1
I thought that the second call should return 2
code here – http://jsfiddle.net/JUKWN/
For the second call to work, you need this:
Your code is putting a static representation of the value of
_ainto the data structure that it’s returning, not dynamically getting it’s value from the actual source. You need a getter function in order to dynamically get it’s value for all data types. What you had would actually work if _a had an array or object in it (because they are always by reference), but not when it’s a simple type like a number or string (which is not by reference).The code I’ve suggested will work for all values of
_a.