DIV CSS 佈局教程網

JavaScript 匿名函式與模組封裝解析
編輯:關於JavaScript     

研究了不同 JS 函式庫的封裝後,終於有了點頭緒。大致就是:

復制代碼 代碼如下:
創建一個自調用匿名函數,設計參數window,並傳入window對象。

而這個過程的目的則是:

復制代碼 代碼如下:
使得自身的代碼不會被其他代碼污染,同時也可以不污染其他代碼。

jQuery 封裝

找了個早期版本的 jQuery(1.7.1),其封裝程式碼大致如下:

復制代碼 代碼如下:
(function( window, undefined ) {
var jQuery = (function() {console.log('hello');});
window.jQuery = window.$ = jQuery;
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
    define( "jquery", [], function () { return jQuery; } );
}
})( window );

其中的 console.log('hello') 是用來驗證是否如開頭所述運作,於是我們就能在 window 上呼叫 jQuery:

復制代碼 代碼如下:
window.$

或者

復制代碼 代碼如下:
window.jQuery

於是我們可以建立一個類似的封裝:

復制代碼 代碼如下:
(function(window, undefined) {
    var PH = function() {

    }
})(window)

相較於上面只是少了兩步:1. 定義 jQuery 符號及全域呼叫;2. 非同步(AMD)支援。

於是又找了更早期 jQuery 的封裝,方法大致相同,除了:

復制代碼 代碼如下:
if (typeof window.jQuery == "undefined") {
    var jQuery = function() {};
    if (typeof $ != "undefined")
        jQuery._$ = $;

    var $ = jQuery;
};

很特別的判斷方式。於是想看看最新 jQuery(2.1.1)的封裝,發現除了增加許多功能外,思想基本相同:

復制代碼 代碼如下:
(function(global, factory) {

    if (typeof module === "object" && typeof module.exports === "object") {
        module.exports = global.document ?
            factory(global, true) :
            function(w) {
                    if (!w.document) {
                    throw new Error("jQuery requires a window with a document");
                }
            return factory(w);
        };
    } else {
        factory(global);
    }

}(typeof window !== "undefined" ? window : this, function(window, noGlobal) {
    var jQuery = function() {
        console.log('jQuery');
    };
    if (typeof define === "function" && define.amd) {
        define("jquery", [], function() {
            return jQuery;
        });
    };
    strundefined = typeof undefined;
    if (typeof noGlobal === strundefined) {
        window.jQuery = window.$ = jQuery;
    };
    return jQuery;
}));

在瀏覽器環境下 typeof module 為 "undefined",因此上面那段是針對 Node.js 等環境的判斷,也反映 jQuery 正變得龐大。

Backbone 封裝

打開 Backbone 看了一下:

復制代碼 代碼如下:
(function(root, factory) {

    if (typeof define === 'function' && define.amd) {
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
            root.Backbone = factory(root, exports, _, $);
        });

    } else if (typeof exports !== 'undefined') {
        var _ = require('underscore');
        factory(root, exports, _);

    } else {
        root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
    }

}(this, function(root, Backbone, _, $) {
    Backbone.$ = $;
    return Backbone;

}));

除了非同步支援,也體現了它對 jQuery 與 underscore 的依賴:

復制代碼 代碼如下:
        define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
            root.Backbone = factory(root, exports, _, $);
        });

這表明 Backbone 原生支援 requirejs。

Underscore 封裝

接著看 Underscore,發現這個庫占領了符號 _:

復制代碼 代碼如下:
(function() {
    var root = this;
    var _ = function(obj) {
        if (obj instanceof _) return obj;
        if (!(this instanceof _)) return new _(obj);
        this._wrapped = obj;
    };

    if (typeof exports !== 'undefined') {
        if (typeof module !== 'undefined' && module.exports) {
            exports = module.exports = _;
        }
        exports._ = _;
    } else {
        root._ = _;
    }

    if (typeof define === 'function' && define.amd) {
        define('underscore', [], function() {
            return _;
        });
    }
}.call(this));

整體上也與前面類似,都是匿名函式,只是最後用的是 call() 方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved