Module Pattern
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
The first step is setting up a namespace. Let’s use the namespace() function from earlier in this chapter and start an example utility module that provides useful array methods:
MYAPP.namespace('MYAPP.utilities.array');
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:
MYAPP.utilities.array = (function () { return {
// todo... };
}());
Next, let’s add some methods to the public interface:
MYAPP.utilities.array = (function () { return {
inArray: function (needle, haystack) {
// ... },
isArray: function (a) {
// ... }
}; }());
Using the private scope provided by the immediate function, you can declare some private properties and methods as needed. Right at the top of the immediate function will also be the place to declare any dependencies your module might have. Following the variable declarations, you can optionally place any one-off initialization code that helps set up the module. The final result is an object returned by the immediate function that contains the public API of your module:
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 };
}());
The module pattern is a widely used and highly recommended way to organize your code, especially as it grows.
댓글 없음:
댓글 쓰기