翻開任何一個 JS 庫的源碼,開頭幾乎都是同一個套路:一個自調用的匿名函數,把 window 作為參數傳進去。這篇文章通過對比 jQuery、Backbone、Underscore 的封裝方式,把這個模式講清楚。
(function( window, undefined ) {
// 這裡的所有變量都是私有的
})( window );
目的很明確:讓自身代碼不污染全局作用域,同時也不被外部代碼影響。傳入 window 是為了在函數內部有一個局部引用,訪問全局對象時不必逐層查找作用域鏈,順帶還能提升一點性能;不傳 undefined 參數則是為了在局部得到一個保證未被污染的 undefined。
以 1.7.1 版本為例,簡化後大致是:
(function( window, undefined ) {
var jQuery = (function() { /* 構造函數主體 */ });
window.jQuery = window.$ = jQuery;
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
三件事:定義 jQuery 對象、掛到全局的 $ 與 jQuery、支持 AMD 異步加載。更早期的版本還多了一步兼容性判斷:
if (typeof window.jQuery == "undefined") {
var jQuery = function() {};
if (typeof $ != "undefined") jQuery._$ = $; // 保留衝突前的 $
var $ = jQuery;
}
這段邏輯用來避免與頁面上已有的 $ 庫(比如 Prototype)互相覆蓋。
到了 2.x,封裝變成了 UMD 風格,同時兼顧 CommonJS、AMD 與全局:
(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() { ... };
if (typeof define === "function" && define.amd) {
define("jquery", [], function() { return jQuery; });
}
if (typeof noGlobal === strundefined) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
注意 typeof module === "object" 在瀏覽器裡是 undefined,所以那個分支專門服務於 Node.js 環境——這也側面說明 jQuery 開始向服務端滲透。
(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;
}));
除了 UMD 三段判斷,這裡還明確聲明了對 underscore 與 jQuery 的依賴;最後那個 root.jQuery || root.Zepto || root.ender || root.$ 鏈,體現了它對多種 DOM 庫的兼容姿態。
(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(this) 而非直接調用,這在某些嚴格模式或模塊環境下能更準確地拿到全局對象。另外那個 if (!(this instanceof _)) return new _(obj) 的小技巧也很值得記:它讓 _({...}) 這種不帶 new 的調用方式同樣可用。