Search code examples
javascriptscoperevealing-module-pattern

Revealing Module Pattern And Scope


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 *

Solution

  • 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.