您的位置:首页 > Web前端 > JQuery

jquery源码中入口部分解析

2016-07-26 18:10 543 查看
jquery入口代码简化后:
  jQuery=function(selector,context){
returnnewjQuery.fn.init(selector,context,rootjQuery);
},

jQuery.fn=jQuery.prototype={
init:function(){
returnthis;
}
}
jQuery.fn.init.prototype=jQuery.fn;
  问题一:为什么不直接用newJquery()创建实例?
  jQuery=function(selector,context){
returnnewjQuery();
},
      因为newjQuery()会陷入无限循环中!!!  问题二:那jQuery是如何创建实例的?
jQuery=function(selector,context){
returnnewjQuery.fn.init(selector,context,rootjQuery);
},

jQuery.fn=jQuery.prototype={
init:function(){
returnthis;//this就是{},它是一个新对象
}
}
      jQuery创建实例实际就是调用它原型中的init方法,通过返回一个新对象从而来创建,这里返回的this就是新对象。 (其实new一个对象,就是新建一个空对象,如果new的这个函数中有this.name=name或者this.show=function(){},那么这个新建对象就会有这些属性和方法了)   问题三:那返回的实例对象只能调用init方法内赋值给this关键字的属性,它又是怎样调用jQuery原型上的方法的呢?
jQuery.fn.init.prototype=jQuery.fn;
     这里将jQuery原型给了init原型,即动态的给init函数添加了jQuery内所有的属性和方法,并且赋予了this(即创建的新对象)。

比如:Water原型未给之前:
    functionAnimate(){
returnnewAnimate.prototype.init();
}
Animate.prototype={
init:function(){
this.name='我的姓名';
returnthis;
}
}

functionWater(){
}
Water.prototype={
waterName:"水的名字",
show:function(){
console.log("我是水方法");
}
}

console.log(Animate().name);//我的姓名
console.log(Animate().waterName);//undefined
Animate().show();//Animate(...).showisnotafunction

     Water原型未给之后:
    functionAnimate(){
returnnewAnimate.prototype.init();
}
Animate.prototype={
init:function(){
this.name='我的姓名';
returnthis;
}
}

functionWater(){
}
Water.prototype={
waterName:"水的名字",
show:function(){
console.log("我是水方法");
}
}
Animate.prototype.init.prototype=Water.prototype;

console.log(Animate().name);//我的姓名
console.log(Animate().waterName);//水的名字
Animate().show();//我是水方法
       它的实现原理:就是把Water原型上的属性、方法指向了init函数对象,这样创建的init新对象就可以调用Water原型了        问题四:为什么要用new?
 jQuery=function(selector,context){
returnnewjQuery.fn.init(selector,context,rootjQuery);
},

jQuery.fn=jQuery.prototype={
init:function(){
returnthis;
}
}
   1、如果不用new,init函数中this不管怎样都是返回的jQuery.fn,那么$('#div')和$('.box')返回的都是同一个对象即jQuery.fn,这样写init方法就没有任何意义!
  2、方便拓展插件,而不破坏jQuery的原型结构
    jQuery.fn=jQuery.prototype={
init:function(){
returnthis;
}
show:function(){
returnthis;
}
}
jQuery().show();

总结:通过newjQuery.fn.init()构建一个新的对象,拥有init构造器的prototype原型对象的方法通过改变prorotype指针的指向,让这个新的对象也指向了jQuery类的原型prototype所以这样构建出来的对象就继承了jQuery.fn原型定义的所有方法了

          
             

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: