I thought that I could use a setter to change a closure variable, but when I access the variable directly it's unchanged. Only when I access it using a getter do I get the expected reassigned variable. Is there a second variable being created in some different scope? What is happening here?
var obj = (function () {
var name = "one";
var setName = function(strName) {
name = strName;
};
var getName = function() {
return name;
};
return {
name: name,
setName: setName,
getName: getName
};
}());
obj.setName("two");
alert("obj.name is: " + obj.name); // Prints "one", but why not "two"?
alert("obj.getName() is: " + obj.getName()); // Prints "two" as I'd expect.
I've added the example above to a fiddle