目前阅读的是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);