英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论