jQuery 中最常用的鞋厂函数是 $()。 它本质上是一个DOM对象,但是它使用的方法都封装在jQuery中,所以我们不能通过$()来使用JavaScript。 同样的 DOM 对象在 jQuery 上也无法使用技巧
我们从$开始,引出jQuery的整个结构
以jQuery 1.11.3版本为例,$作为函数名出现的地方是在源码的最后:
window.jQuery = window.$ = jQuery;
其中jquery 定义函数,jQuery是上面定义的一个函数,出现在源码第70行
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
}
该函数相当于鞋工厂函数,内部返回一个对象,这样就可以不用new方法来创建jQuery对象
所以new $().xxx和$().xxx没有区别jquery 定义函数,这也符合jQuery“write less, do more”的设计理念
源代码第2882行:
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
init的原型对象被替换为jQuery.fn,实际上是被jQuery函数本身的原型对象jQuery.prototype替换。
源代码第89行:
jQuery.fn = jQuery.prototype
这样我们就可以轻松的编写jQuery的扩展方法了
举个反例:
jQuery.fn.alertMsg = function(msg){
alert('msg');
}
使用:
$().alertMsg('Hello World!');
jQuery的整体结构就差不多到这里了
下面是一个简化版的jQuery框架,方便理解
(function () {
function jQuery(selector) {
return new jQuery.prototype.init(selector);
}
// jQuery对象的构造函数
jQuery.prototype.init = function (selector) {
}
// jQuery原型上的css方法
jQuery.prototype.css = function (config) {
}
// 将jQuery原型上的方法都放到init的原型链上
jQuery.prototype.init.prototype = jQuery.prototype;
window.$ = window.jQuery = jQuery;
})();
关系图: