A private variable is inaccessible and cannot be altered by code outside of the module or class that owns it.
For instance, attempting to retrieve aModule.privateVar
will not yield any results.
Your publicFunction
acts as a "getter" in Java (and similar languages), providing read-only access to the private variable's value.
In the given scenario, you are not actually modifying the private variable; rather, you are creating a new variable within the scope of publicFunction
and assigning a value to it. Despite sharing the same name (privateVar
), they occupy separate memory spaces.
I have made modifications to your code for clarity:
var aModule = (function() {
var privateVar = 1;
return {
publicFunction: function() {
return privateVar;
},
getPrivateVar() {
return privateVar;
}
}
})();
aModule.publicFunction = function() {
privateVar = function() {
console.log('new content');
}
privateVar();
};
aModule.publicFunction(); // 'new content'
console.log(aModule.getPrivateVar()); //outputs 1
To delve deeper into why this occurs, it all boils down to scope. privateVar exists within the scope of an anonymous function. This function returns an object with multiple functions defined within it. Upon invocation, this object is assigned to aModule but retains access to privateVar due to shared scope.
However, beyond that function's scope, we reside in a different realm lacking access to aModule's variables, save for those exposed through the returned object.