The Module Pattern Module模式
jQuery, Dojo, ExtJS, YUI都用到了这种模式
"I'm currently in the process of writing a large-scale JavaScript application based on this pattern, and I have to say, it's a delight." ---- Brian Cray
优点
- Cleaner approach for developers 更加干净的接口
- Supports private data 支持私有数据
- Less clutter in the global namespace 在全局命名空间没那么杂乱
- Localization of functions and variables throught closures 通过闭包对方法和变量的本地化
缺点
- 私有方法无法访问,可能会不易测试
- 因为私有方法和函数不可访问,因此它们缺少可扩展性
例子一
( function( window, undefined ) {
// normally variables & functions start with a lowercase letter but with modules, that is not the case.
// The general tradition is to start them with a capital letter instead.
function MyModule() {
// `this` refers to the instance of `MyModule` when created
this.myMethod = function myMethod() {
alert( 'my method' );
};
// note that we still use a function declaration even when using a function expression.
// for more information on why, check out: http://kangax.github.io/nfe/
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
}
// expose access to the constructor
window.MyModule = MyModule;
} )( window );
// example usage
var myModule = new MyModule();
myModule.myMethod(); // alerts "my method"
myModule.myOtherMethod(); // alerts "my other method"
例子二
var MyModule = ( function( window, undefined ) {
// this object is used to store private variables and methods across multiple instantiations
var privates = {};
function MyModule() {
this.myMethod = function myMethod() {
alert( 'my method' );
};
this.myOtherMethod = function myOtherMethod() {
alert( 'my other method' );
};
}
return MyModule;
} )( window );
// example usage
var myMod = new MyModule();
myMod.myMethod(); // alerts "my method"
myMod.myOtherMethod(); // alerts "my other method"