模块模式的知识
在类对象之上构建一个灵活的工程模块(对象设计),便多人协作
模块(的黑箱功能)方便程序随时间的变化的扩展功能
The module pattern is widely used because it provides structure and helps organize your code as it grows. Unlike other languages, JavaScript doesn’t have special syntax for packages, but the module pattern provides the tools to create self-contained de- coupled pieces of code, which can be treated as black boxes of functionality and added, replaced, or removed according to the (ever-changing) requirements of the software you’re writing.
模块创建的基础
模块模式是以下多种基础模式(对象设计)的综合应用 The module pattern is a combination of several patterns described so far in the book, namely: Namespaces Immediate functions Private and privileged members Declaring dependencies
JS模块的形式创建
-
1 可选将模块纳入某名字空间内
The first step is setting up a namespace.
-
2 使用闭包技术创建模块(闭包可创建类对象,这里它用)
闭包返回的对象,即为模块的公共接口(public interface是模块的重要形式属性,因模块常作共用) The next step is defining the module. The pattern uses an immediate function that will provide private scope if privacy is needed. The immediate function returns an object—the actual module with its public interface, which will be available to the consumers of the module:
-
3 实现
可利闭包私有性,和返回对象的公开性实现你的模块逻辑 Next, let’s add some methods to the public interface:
MYAPP.utilities.array = (function () {
return {
inArray: function (needle, haystack) {
// ...
},
isArray: function (a) {
// ...
}
};
}());
- 4 一个数组算法模块
注意标准模块使用了 namespace dependencies private properties public API
MYAPP.namespace('MYAPP.utilities.array');
MYAPP.utilities.array = (function() {
// dependencies
var uobj = MYAPP.utilities.object,
ulang = MYAPP.utilities.lang,
// private properties
array_string = "[object Array]",
ops = Object.prototype.toString;
// private methods
// ...
// end var
// optionally one-time init procedures
// ...
// public API
return {
inArray: function(needle, haystack) {
for (var i = 0, max = haystack.length; i < max; i += 1) {
if (haystack[i] === needle) {
return true;
}
}
},
isArray: function(a) {
return ops.call(a) === array_string;
}
// ... more methods and properties
};
}());