首页 / JQUERY / jQuery的框架介绍
jQuery的框架介绍
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了jQuery的框架介绍,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3061字,纯文字阅读大概需要5分钟。
内容图文
![jQuery的框架介绍](/upload/InfoBanner/zyjiaocheng/353/db6c365962864d3a81c89b68afc21cad.jpg)
jQuery使用有一段时间了,但是有一些API的实现实在想不通。小编参考相关资料源码,现在把我的学习过程和收获分享给大家。
下面将使用简化的代码来介绍,主要关注jQuery的实现思想~>_<~
//匿名立即执行函数 //.防止污染全局空间 //.选择性保护内部变量 (function(window, undefined){ //第二参数undefined设置而不传的原因: // 外部发生这种情况:var undefined = 时,undefined会被篡改 // 设置第二参数而不传,则undefined就会被重置回原来值 function jQuery(sel){ return new jQuery.prototype.init(sel); } jQuery.prototype = { constructor: jQuery, init: function(sel){ if(typeof sel === 'string'){ var that = this; //jQuery内部使用的是Sizzle,这里使用querySelectorAll替代 var nodeList = document.querySelectorAll(sel); Array.prototype.forEach.call(nodeList, function(val, i){ that[i] = val; }) this.selector = sel; this.length = nodeList.length; } } } jQuery.prototype.init.prototype = jQuery.prototype; //对外暴露jQuery:将jQuery绑定在window上面 window.$ = jQuery; })(window);
--------------------------
jQuery一开始使用匿名立即执行函数包裹其内部,并在第5行对外暴露;
所谓的匿名立即执行函数即这个函数是匿名的(没有名字)、定义完后立即调用的;
当我们在外部调用$("div")时,其实调用的就是内部的jQuery("div");
(function(window, undefined){ //内部变量 //对外暴露jQuery:将jQuery绑定在window上面 window.$ = jQuery; })(window); $("div")
--------------------------
好,接下来稍复杂点,下面的代码主要实现如图的互相引用:
以$('div')调用为例:
从第2行代码可以看出,jQuery使用jQuery.prototype.init来实例化jQuery对象,但这会带来一个问题:
实例化的对象只能访问到init下的变量,而不能访问到jQuery.prototype(jQuery对外提供的API绑定在该对象下)。
于是乎,补写第21行代码,将init.prototype指向jQuery.prototype即可。
这样就完成了,使用init来实例化,且可以在init作用域下访问到jQuery.prototype。
function jQuery(sel){ return new jQuery.prototype.init(sel); } jQuery.prototype = { constructor: jQuery, init: function(sel){ if(typeof sel === 'string'){ var that = this; //jQuery内部使用的是Sizzle,这里使用querySelectorAll替代 var nodeList = document.querySelectorAll(sel); Array.prototype.forEach.call(nodeList, function(val, i){ that[i] = val; }) this.selector = sel; this.length = nodeList.length; } } } jQuery.prototype.init.prototype = jQuery.prototype;
为什么使用jQuery.prototype.init来实例化对象,而不直接使用jQuery函数呢?
假设使用jQuery函数来实例化对象,这样对象之间的引用的确可以简化为 jQuery-->jQuery.prototype。
但是调用会变得繁琐起来:new $('div'),所以基于这个考虑(猜测(⊙0⊙)),在内部使用较为复杂的实现,来简化调用。
--------------------------
好,最后,再来看一下init的实现。同样也简化了代码,只实现了最常用的一种情况。
jQuery会把获取到的nodeList处理成数组(方便后续使用),并在其下挂载一些变量,如length,selector。
init: function(sel){ if(typeof sel === 'string'){ var that = this; //jQuery内部使用的是Sizzle,这里使用querySelectorAll替代 var nodeList = document.querySelectorAll(sel); Array.prototype.forEach.call(nodeList, function(val, i){ that[i] = val; }) this.selector = sel; this.length = nodeList.length; } }
本文所述到此结束,下篇文章将给大家介绍jQuery链式调用与show知识浅析,欲了解更多资讯敬请关注脚本之家网站!
内容总结
以上是互联网集市为您收集整理的jQuery的框架介绍全部内容,希望文章能够帮你解决jQuery的框架介绍所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。