模块创建构造函数(Modules That Create Constructors)
在前面的例子中,创建了一个MYAPP.utilities.array对象,但有时候使用构造函数创建你的对象更方便,你也可以使用模块模式实现它。
唯一的不同就是在包裹模块的立即执行函数返回一个函数而不是对象。
下面这个例子就是模块模式创建一个构造函数 MYAPP.utilities.Array
MYAPP.namespace('MYAPP.utilities.Array'); MYAPP.utilities.Array = (function () { // dependencies var uobj = MYAPP.utilities.object, ulang = MYAPP.utilities.lang, // private properties and methods... Constr; // end var // optionally one-time init procedures // ... // public API -- constructor Constr = function (o) { this.elements = this.toArray(o); }; // public API -- prototype Constr.prototype = { constructor: MYAPP.utilities.Array, version: "2.0", toArray: function (obj) { for (var i = 0, a = [], len = obj.length; i < len; i += 1) { a[i] = obj[i]; } return a; } }; // return the constructor // to be assigned to the new namespace return Constr; }());这个构造方法的使用方法:
var arr = new MYAPP.utilities.Array(obj);
将全局变量导入模块中(Importing Globals into a Module)
在一般模块模式的变种中,你可以传递参数给包裹模块立即执行函数。你可以传递任何值,但通常都是全局变量的引用甚至全局变量自身。导入全局变量可以加速在立即执行函数中全局符号的解析,因为导入的全局变量变成了函数的局部变量:
MYAPP.utilities.module = (function (app, global) { // references to the global object // and to the global app namespace object // are now localized }(MYAPP, this));