目前閱讀的是jQuery 1.11.3的源碼,有參考nuysoft的資料。原來比較喜歡在本身的Evernote上作學習基類,並無在網上寫技術博客的習慣,如今開始學習JS的開源代碼,想跟你們多交流,但願有所收穫。jquery
(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 ) { // 建立jQuery對象, 其實是jQuery.fn.init所返回的對象 var jQuery = function( selector, context ) { return new jQuery.fn.init( selector, context ); // 若是調用new jQuery, 生成的jQuery會被丟棄,最後返回jQuery.fn.init對象 // 所以能夠直接調用jQuery(selector, context), 不須要使用new } // 建立jQuery對象原型,爲jQuery添加各類方法 jQuery.fn = jQuery.prototype = { // 在調用new jQuery.fn.init後, jQuery.fn.iniy.prototype = jQuery.fn = jQuery.prototype // 至關於將全部jQuery.fn的方法都掛載到一開始jQuery函數返回的對象上 ... } init.prototype = jQuery.fn; // 建立jQuery.extend方法 jQuery.extend = jQuery.fn.extend = function() {、 ... } // 使用jQuery.extend擴展靜態方法 jQuery.extend({}); // 爲window全局變量添加$對象 if ( typeof noGlobal === strundefined ) { // var strundefined = typeof undefined window.jQuery = window.$ = jQuery; } return jQuery; }));
爲了保證不污染全局變量,jQuery源碼中將全部的對象及方法建立都放到了factory函數中執行。經過形參global來傳遞window變量,在利用factory建立jQuery對象之前,首先進行window變量的檢測。函數
window檢測代碼部分有英文註釋源碼分析
// For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info
module 和 module.exports主要是爲了讓jQuery可以以模塊的形式注入到沒有window.document變量的諸如Node.js的運行環境中,當遇到這種狀況,就不會在window中設置jQuery$變量。要使用jQuery時,則是使用所返回的jQuery對象,如在Node.js中:學習
var jQuery = require("jquery")(window);