//匿名立即执行函数//.防止污染全局空间//.选择性保护内部变量(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); --------------------------(function(window, undefined){//内部变量//对外暴露jQuery:将jQuery绑定在window上面window.$ = jQuery;})(window);$("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函数呢?
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知识浅析,欲了解更多资讯敬请关注脚本之家网站!