Reputation: 3272
I ran into an issue with some javascript I was running and broke it down to the code below. I'm confused as to why the _localVar
variable doesn't change after init()
is called. I find that if I reference this._localVar
in the revealingModule, the results are as expected. I am confused about the scope. Could someone please clarify why this is occurring. I thought that if I didn't use this
, then the next scope would be the module, but I don't think that's happening.
var myRevealingModule = (function () {
var _localVar = "Default";
function init() {
console.log(_localVar);
_localVar = "Init";
}
function getTest() {
console.log(_localVar);
}
return {
init: init,
getTest: getTest,
localVar: _localVar
};
})();
myRevealingModule.getTest(); // "Default"
console.log(myRevealingModule.localVar); // "Default"
myRevealingModule.init(); // "Default"
myRevealingModule.getTest(); // "Init"
console.log(myRevealingModule.localVar); // "Default" * WHY *
Upvotes: 1
Views: 256
Reputation: 5241
Note that your module uses a self-invoking function. Therefore the value of myRevealingModule.localVar
is determined right after the definition and built-in invocation of myRevealingModule
. At this time the value of _localVar
is "Default", which is copied to returned object's localVar
property. Even if you change _localVar
afterwards this has no effect on myRevealingModule.localVar
anymore.
Basically the following example show the same effect:
var a = 42;
var b = a;
console.log(a); // 42
console.log(b); // 42
a = 84;
console.log(a); // 84
console.log(b); // 42
b
copies the value of a
. If you change a
afterwards that has no impact on b
.
Upvotes: 1
Reputation: 33399
myRevealingModule.localVar
is not a reference to the variable's value; it simply copied the string when it's created.
When you use this.localVar
, you're using the variable in the returned object. Hence, when you change that identifier, it also updates with myRevealingModule.localVar
.
Upvotes: 1