0

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/

2 Answers 2

3

For the second call to work, you need this:

var f = function(a){
   var _a = a;

   return {
       getA : function() {
           return(_a);
       },
       setA : function(e){
          _a = e;
       }
   }        
}; 

Your code is putting a static representation of the value of _a into 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.

Sign up to request clarification or add additional context in comments.

Comments

1

You don't have a real getter function. You're just assigning the value of _a to a property of your returned object literal. Modify your code like this

return {
   getA : function() {
       return(_a);
   },
   setA : function(e){
      _a = e;
   }
};     

var d = f(1);
console.log(d.getA()); // 1

d.setA(2);
console.log(d.getA()); // 2

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.