简体   繁体   English

显示模块模式和范围

[英]Revealing Module Pattern And Scope

I ran into an issue with some javascript I was running and broke it down to the code below. 我遇到了一些我正在运行的JavaScript的问题,并将其分解为以下代码。 I'm confused as to why the _localVar variable doesn't change after init() is called. 我对为什么init()调用后_localVar变量不更改感到困惑。 I find that if I reference this._localVar in the revealingModule, the results are as expected. 我发现如果我在this._localVar中引用this._localVar ,则结果与预期的一样。 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. 我以为如果不使用this ,那么下一个作用域将是模块,但是我认为这没有发生。

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 *

myRevealingModule.localVar is not a reference to the variable's value; myRevealingModule.localVar不是对变量值的引用; it simply copied the string when it's created. 它只是在创建字符串时复制了该字符串。

When you use this.localVar , you're using the variable in the returned object. 使用this.localVar ,将在返回的对象中使用变量。 Hence, when you change that identifier, it also updates with myRevealingModule.localVar . 因此,当您更改该标识符时,它也会使用myRevealingModule.localVar更新。

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 . 因此, myRevealingModule.localVar的值是在定义和内置调用myRevealingModule之后myRevealingModule.localVar确定的。 At this time the value of _localVar is "Default", which is copied to returned object's localVar property. 此时_localVar值为“默认”,该值将复制到返回的对象的localVar属性中。 Even if you change _localVar afterwards this has no effect on myRevealingModule.localVar anymore. 即使之后更改_localVar ,它也不再对myRevealingModule.localVar

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 . b副本的值a If you change a afterwards that has no impact on b . 如果您更改a之后,则对b没有影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM