我一直在研究为我的团队提出标准化的 Javascript 编码风格。大多数资源现在推荐涉及闭包的“模块”模式,例如:
var Module = function() {
someMethod = function() { /* ... */ };
return {
someMethod: someMethod
};
}();
并像 Module.someMethod();
一样调用它。这种方法似乎只适用于传统 OOP 上下文中的静态方法,例如用于获取/保存数据的存储库类、用于发出外部请求的服务层等。除非我遗漏了什么,否则模块模式不打算与通常需要传递给服务方法或从服务方法传递给 UI 粘合代码的数据类(想想 DTO)一起使用。
我看到引用的一个共同好处是,您可以使用模块模式在 Javascript 中拥有真正的私有(private)方法和字段,但这也可以与一起实现,能够拥有静态或 具有类似于此的“经典”Javascript 样式的实例方法:
myClass = function(param) {
// this is completely public
this.publicProperty = 'Foo';
// this is completely private
var privateProp = param;
// this function can access the private fields
// AND can be called publicly; best of both?
this.someMethod = function() {
return privateProp;
};
// this function is private. FOR INTERNAL USE ONLY
function privateMethod() {
/* ... */
};
}
// this method is static and doesn't require an instance
myClass.staticMethod = function() { /* ... */ };
// this method requires an instance and is the "public API"
myClass.prototype.instanceMethod = function() { /* ... */ };
所以我想我的问题是什么使模块模式比传统风格更好?它更简洁一些,但这似乎是唯一显而易见的好处;事实上,传统风格似乎提供了提供真正封装的能力(类似于真正的 OOP 语言,如 Java 或 C#),而不是简单地返回静态方法的集合。
有什么我想念的吗?
最佳答案
模块模式也可用于创建原型(prototype),参见:
var Module = function() {
function Module() {};
Module.prototype.whatever = function() {};
return Module
}();
var m = new Module();
m.whatever();
正如另一位发帖者所说,干净的全局 namespace 是它的原因。然而,实现这一目标的另一种方法是使用 AMD 模式,它也解决了其他问题,如依赖管理。它还将所有内容包装在某种闭包中。这是一个很棒的Introduction to AMD代表异步模块定义。
我还推荐阅读 JavaScript Patterns因为它彻底涵盖了各种模块模式的原因。
关于javascript - Javascript 模块模式有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625042/