ES5模块模式用法

huangapple go评论75阅读模式
英文:

ES5 Module pattern usage

问题

两种方法(FirstModule 和 SecondModule)之间的区别是什么?

var MyModule = (function () {
    return {
        method: function () {
            console.log("MyModule:method");
        }
    }
})();

var FirstModule = (function () {
    return {
        test: function () {
            MyModule.method();
        }
    }
})();

var SecondModule = (function (myMethod) {
    return {
        test: function () {
            myMethod.method(); 
        }
    }
})(MyModule);

在这两种情况下,我们都有相同的对象,它不是一个副本。我会感激任何关于任何方法的好信息、优点和缺点。

英文:

Could you explain to me what is the difference between that two approaches (FirstModule and SecondModule:

var MyModule = (function () {
    return {
        method: function () {
            console.log("MyModule:method");
        }
    }
})();

var FirstModule = (function () {
    return {
        test: function () {
            MyModule.method();
        }
    }
})();

var SecondModule = (function (myMethod) {
    return {
        test: function () {
            myMethod.method(); 
        }
    }
})(MyModule);

In both cases we have the same object, it isn't a copy. I would be grateful for any good information, advantages, disadvantages of any approach.

答案1

得分: 1

第一种方法使用MyModule变量,该变量可以被其他代码覆盖,模块外,在FirstModule值被分配之后。

第二种方法使用myMethod变量,该变量不能(尽管分配给myMethod的对象的属性仍然可以,因为该对象仍然可以通过MyModule变量在全局范围内访问)。

英文:

The first approach uses the MyModule variable, which can be overwritten by other code, outside the module, after the FirstModule value has been asigned.

The second uses the myMethod variable, which can't (although properties of the object assigned to myMethod still can because that object is still globally available via the MyModule variable).

huangapple
  • 本文由 发表于 2020年1月3日 19:00:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定