jQuery源码学习1--jQuery对象的构建
先放上一段jQuery精简的源码(版本1.3.2);

1 (function( window, undefined ) { 2 3 var jQuery = (function() { 4 var jQuery = function( selector, context ) { 5 return new jQuery.fn.init( selector, context, rootjQuery ); 6 } 7 8 jQuery.fn = jQuery.prototype = { 9 constructor: jQuery, 10 init: function( selector, context, rootjQuery ) { 11 12 } 13 }; 14 15 // Give the init function the jQuery prototype for later instantiation 16 jQuery.fn.init.prototype = jQuery.fn; 17 18 jQuery.extend = jQuery.fn.extend = function() {}; 19 20 jQuery.extend({ 21 22 }); 23 24 return jQuery; 25 26 })(); 27 28 window.jQuery = window.$ = jQuery; 29 })(window);
(function( window, undefined ) { var jQuery = (function() { // 构建jQuery对象 var jQuery = function( selector, context ) { return new jQuery.fn.init( selector, context, rootjQuery ); } ...
这么多jQuery看着有点头大,自己改改把里面的jQuery换成jq(个人习惯,不喜欢外部与内部使用相同的变量名);
1 (function( window, undefined ) { 2 var jQuery = (function() { 3 var jq = function( selector, context ) { 4 return new jq.fn.init( selector, context, rootjQuery ); 5 } 6 7 jq.fn = jq.prototype = { 8 constructor: jq, 9 init: function( selector, context, rootjQuery ) { 10 console.log("I'm init ..."+(new Date()).getTime()); 11 } 12 }; 13 14 jq.fn.init.prototype = jq.fn; 15 16 jq.extend = jq.fn.extend = function() {}; 17 18 jq.extend({ 19 }); 20 21 return jq; 22 23 })(); 24 25 window.jQuery = window.$ = jQuery; 26 })(window);
接着看代码
最外层 (function( window, undefined ) {})() 自动执行;
接着 var jQuery = (function() {}...
return jq;
)() 继续自动执行;
以上外层代码可以略过...
通过源码可以看到其实jQuery=jq;所以重点关注下关键的jq;
(function( window, undefined ) { var jQuery = (function() { // 构建jq对象 var jq = function( selector, context ) { return new jq.fn.init( selector, context, rootjQuery ); } // jq对象原型 jq.fn = jq.prototype = { constructor: jq, init: function( selector, context, rootjQuery ) { //... } }; jq.fn.init.prototype = jq.fn; // 合并内容到第一个参数中,后续大部分功能都通过该函数扩展 // 通过jq.fn.extend扩展的函数,大部分都会调用通过jq.extend扩展的同名函数 jq.extend = jq.fn.extend = function() {}; // 在jq上扩展静态方法 jq.extend({ });
// 到这里,jq对象构造完成 return jq; })(); window.jQuery = window.$ = jQuery; })(window);
jq对象是通过
return new jq.fn.init( selector, context, rootjQuery );创建的,而不是jq();
jq.fn = jq.prototype;
jq.fn可以作为特权方法,也可以作为原型方法调用,说不太清楚,暂时这样理解
比如 jQuery('args').init();
jQuery.fn.init();
jq.fn.init.prototype = jq.fn;
为构造函数return new jq.fn.init( selector, context, rootjQuery );创建的对象指向相同的fn对象;
很乱,暂时作为自己的学习记录吧