JavaScript學習筆記(二十四) 模塊創建構造函數

 模塊創建構造函數(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));



發佈了4 篇原創文章 · 獲贊 27 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章