最近在看jQuery源码,jQuery 1.3.0中core.js 524行中$.fn.init.prototype = $.fn,并且很多api(比如说css,index等)是定义在$.fn上,$()是一个工厂返回的是$.fn.init的实例,因为$.fn.init的原型指向$.fn,因此$.fn.init可以继承$.fn上的所有方法,可是不觉着这种对象本身的一个属性的原型指向本身很怪吗?为什么不把$.fn.init定义成另一个对象(比如说$.init),然后原型指向$.fn($.init.prototype = $.fn)?
天蓬老师2017-04-10 15:53:25
试了一下,好像确实没什么区别。唯一的一点就是如果把init
定义成jQuery.init
以后,生成的jQuery
对象少了一个init
方法,因为此时原型对象上不再有init
了。不过这个应该没有关系,会有需要直接调用init
方法的场合吗。
// 原方法生成的jQuery对象中具有的属性
0 length context selector init jquery size get pushStack setArray each index
attr css text wrapAll wrapInner wrap append prepend before after end push find
clone filter closest not add is hasClass val html replaceWith eq slice map
andSelf domManip extend parent parents next prev nextAll prevAll siblings
children contents appendTo prependTo insertBefore insertAfter replaceAll
removeAttr addClass removeClass toggleClass remove empty data removeData queue
dequeue bind one unbind trigger triggerHandler toggle hover ready live die blur
focus load resize scroll unload click dblclick mousedown mouseup mousemove
mouseover mouseout mouseenter mouseleave change select submit keydown keypress
keyup error _load serialize serializeArray ajaxStart ajaxStop ajaxComplete
ajaxError ajaxSuccess ajaxSend show hide _toggle fadeTo animate stop slideDown
slideUp slideToggle fadeIn fadeOut offset position offsetParent scrollLeft
scrollTop innerHeight outerHeight height innerWidth outerWidth width
// 新的方式生成的jQuery对象中的属性,仅少了一个init方法
0 length context selector jquery size get pushStack setArray each index
attr css text wrapAll wrapInner wrap append prepend before after end push find
clone filter closest not add is hasClass val html replaceWith eq slice map
andSelf domManip extend parent parents next prev nextAll prevAll siblings
children contents appendTo prependTo insertBefore insertAfter replaceAll
removeAttr addClass removeClass toggleClass remove empty data removeData queue
dequeue bind one unbind trigger triggerHandler toggle hover ready live die blur
focus load resize scroll unload click dblclick mousedown mouseup mousemove
mouseover mouseout mouseenter mouseleave change select submit keydown keypress
keyup error _load serialize serializeArray ajaxStart ajaxStop ajaxComplete
ajaxError ajaxSuccess ajaxSend show hide _toggle fadeTo animate stop slideDown
slideUp slideToggle fadeIn fadeOut offset position offsetParent scrollLeft
scrollTop innerHeight outerHeight height innerWidth outerWidth width