zl程序教程

您现在的位置是:首页 >  前端

当前栏目

jQuery的初始化与对象构建之浅析

jQuery对象 构建 浅析 初始化
2023-06-13 09:14:27 时间
小结一下:

1.整个类库定义在一匿名函数中,杜绝了全局变量的产生;
2.将undefined作为缺失的参数传递,防止了undefined变量的污染;
3.可以看出$(...)实际上返回的是jQuery.fn.init对象的实例,随后将该对象的prototype指向了jQuery.prototype(语句jQuery.fn.init.prototype=jQuery.fn),因此产生的实例共享着jQuery.prototype里的方法和属性且实现了链式编程的操作;
4.最后通过window.jQuery=window.$=jQuery将jQuery与$导出为全局变量。

复制代码代码如下:

(function(window,undefined){
//DefinealocalcopyofjQuery
varjQuery=(function(){
varjQuery=function(selector,context){
//ThejQueryobjectisactuallyjusttheinitconstructor"enhanced"
returnnewjQuery.fn.init(selector,context/*,rootjQuery*/);
};
//...
jQuery.fn=jQuery.prototype={
constructor:jQuery,
init:function(selector,context,rootjQuery){
//...
}
//...
};
//GivetheinitfunctionthejQueryprototypeforlaterinstantiation
jQuery.fn.init.prototype=jQuery.fn;
//...
//ExposejQuerytotheglobalobject
returnjQuery;
})();
//...
window.jQuery=window.$=jQuery;
})(window);