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
In your code:
var obj = function () {
var name = "one";
This name is a property of the local variable object. This is the one that setName and getName have a reference to. It is resolved on the scope chain.
return {
name: name,
This name is a property of the returned object, i.e. it's a different "name" and is resolved using object property identify resolution (i.e. which is completely different to resolving identifiers on the scope chain). The line above assigns the current value of the local variable name, there is no closure here.
setName and getName are setting the closed variable, obj.name is not modified by those functions.