Think of it this way: A closure is a reference to the current scope chain. Only something which references the same scope will be modifying the same variable. This section is the scope in which the key
variable exists:
{var key = 200;
return {getKey : function(){return key} };
}
Your set function is defined outside this scope and thus modifies a different variable named key
. Closures and scopes are not connected to objects. If you wanted to be able to add the set function later, you would need to make the variable an actual member of the object:
test = (function(){
return {key: 200, getKey : function(){return this.key} };
})();
test.getKey() //returns 200, so far so good
test.setKey = function(arg){this.key = arg};
test.setKey(400);
test.getKey() //returns 400