Every time we execute the function foo(), we are creating a new object out which is getting returned. Every such out object has two properties getName and setName, both are functions. These functions remember their scope in which they were defined and so these functions are always able to access their own copy of variable name.
My question is where actually is the variable name stored in memory for each out object? It must be stored inside some object (if I am not wrong).
1) Surely it is not stored in the object out, else it would have been accessible using dot notation.
2) Also, it is not stored in the function object foo. Had it been x.setName("JavaScript") would have affected the value of y.getName() but it is not so.
function foo(){
var name="";
out = {
getName: function(){return name;},
setName: function(newName){name = newName}
};
return out;};
var x = foo();
var y = foo();