jQuery源码分析2--全局变量
基于jQuery1.8.3,简单解析15-93行代码。 一、整体结构从15-93行定义了很多全局变量,用变量保存这些数据的方式将提高运行的效率,同时在min版本下也可节省较大的空间。 二、变量含义// A central reference to the root jQuery(document) rootjQuery,// The deferred used on DOM ready readyList,// Use the correct document accordingly with window argument (sandbox) document = window.document,location = window.location,navigator = window.navigator, rootjQuery实际就是document的jQ对象,在906行rootjQuery = jQuery(document),该变量被赋值了。 readyList是一个用于存储延迟对象的变量,用于DOM 的ready事件。 变量document、location、navigator存储了window下的对应的属性。 _jQuery = window.jQuery,_$ = window.$, 这两行代码主要是在noConflict()方法中有用处,这儿就不多说了。 core_push = Array.prototype.push,// array的push方法 core_slice = Array.prototype.slice,// array的slice方法 core_indexOf = Array.prototype.indexOf,// array的indexof方法 core_toString = Object.prototype.toString,// object的toString方法 core_hasOwn = Object.prototype.hasOwnProperty,// object的hasOwnProperty方法 core_trim = String.prototype.trim,// string的trim方法 这些个变量保存了后面会多次用到的一些变量。 从47行到72行是一些正则,到具体用到的地方再讨论。 fcamelCase = function( all,letter ) { return ( letter + "" ).toUpperCase(); } 转驼峰函数的回调函数。 DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded",DOMContentLoaded,false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange",DOMContentLoaded ); jQuery.ready(); } } DOMContentLoaded()方法是DOM加载完成的执行函数,在ready函数时在详细看下。 class2type = {}; class2type主要用于对变量的类型判断。 三、构造函数刚才的变量中少说了一个jQuery的方法。 jQuery = function( selector,context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector,context,rootjQuery ); }, 我们每次调用jQuery()或$()时,实际得到的是jQuery原型上init函数的一个实例。 在return中new的话,可以省去构造函数前的new,方便书写。注:init将在下一节讲述。 其实,fn是prototype的简写,在95行: jQuery.fn = jQuery.prototype = { 当然,我们发现返回的jQ实例可以调用到jQuery对象上的方法,比如$(‘div’).length等。其实在289行 jQuery.fn.init.prototype = jQuery.fn; 我们用jQuery的原型对象覆盖了构造函数init的原型方法,从而使得new后的实例可以访问到jQuery()的原型属性和方法。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |