jquery源码中入口部分解析
2016-07-26 18:10
543 查看
jquery入口代码简化后:
总结:通过newjQuery.fn.init()构建一个新的对象,拥有init构造器的prototype原型对象的方法通过改变prorotype指针的指向,让这个新的对象也指向了jQuery类的原型prototype所以这样构建出来的对象就继承了jQuery.fn原型定义的所有方法了
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原型定义的所有方法了
相关文章推荐
- jQuery.nivo.slider.js 幻灯片图片切换
- php+ajax+jquery实现分页
- jquery - ajax - 400 415错误
- springmvc jquery json ajax
- jquery常用表单&DOM操作方法
- 简单的tab切换(jquery)
- jquery ligerui下拉框赋值问题
- jquery--获取链接参数
- 如何判断jquery选择器选择结果为空
- jQuery DOM基础
- jquery调用jsonp接口
- jquery全选和反全选在第三次点击后无效的问题
- $.ajax的简单用法
- 《锋利的jQuery》学习笔记<1>
- 基于jQuery实现页面搜索功能
- jquery的学习笔记
- JQuery心得(持续更新中)
- 一个简单Jquery Mobile示例
- jquery 产品查看放大镜组件
- jquery判断设置checked