本系列文章以jquery-2.1.4.js为标准,可以从官网下载非压缩的开发版进行查看。
下面先看一jquery的概貌。
jquery的概貌
/*!
* jQuery JavaScript Library v2.1.4
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2015-04-28T16:01Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a 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.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 );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {......})
);
从文件注释中可以看到,jquery.js里包含了另一个js,Sizzle.js。
Sizzle引擎
Sizzle是jQuery的御用选择器引擎,是jQuery作者John
Resig写的DOM选择器引擎,速度号称业界第一。另外,Sizzle是独立的一部分,不依赖任何库,如果你不想用jQuery,可
以只用Sizzle。所以单独拿出来特别对待。
第一个匿名函数function( global, factory ):
这个函数是处理CommonJS环境下创建jquery问题的。jquery不只是在浏览器环境下可以用,我们不用太关心。
这个匿名函数创建后马上传入了参数执行:
(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {......})
其中第二个参数是一个匿名函数,这个才是创建jquery的真正函数,浏览器中global实际为window对象,window对象没有exports属性,所以最后会执行factory( global );
。
所以创建jquery的匿名函数在浏览器中传入了window对象。
后面讨论的内容都是
function( window, noGlobal ) {
......
}
这个匿名函数里的内容。