網(wǎng)上很多jQuery的分析文章慨丐,雖然很詳細(xì),但是對(duì)我這種小白泄私,只想了解一下大概原理房揭,而不想花太多時(shí)間研究細(xì)節(jié),于是我就抽出jQuery綁定元素及方法的核心思想晌端,沒(méi)有圖捅暴,但是相信你一定能看懂。
我們想要$('selector')
時(shí)就獲得一個(gè)元素咧纠,且里面有一些方法蓬痒。
這些方法要綁定在原型prototype
上。
所以jQuery必須是個(gè)構(gòu)造函數(shù)
var $ = new fucntion jQuery(){}
假設(shè)里面有個(gè)方法是綁定元素的漆羔,叫做init梧奢,我們首先要在prototype綁定這個(gè)方法。
jQuery.prototype.init = function(){}
當(dāng)然jQuery里還有其他實(shí)例方法演痒,比如each方法亲轨,那我們需要這樣寫(xiě)。
jQuery.prototype = {
init: function(){},
each: function(callback, args) {},
其他方法...
}
然后我們需要返回這個(gè)元素鸟顺,因此返回的是init方法的執(zhí)行結(jié)果.
var $ = new fucntion jQuery(){
return jQuery.prototy.init(selector)
}
但是我們返回的是init創(chuàng)造的dom惦蚊,因此我們也要在init
里獲取到j(luò)query的原型上的方法,因此最好的辦法是把init函數(shù)也當(dāng)成一個(gè)構(gòu)造函數(shù)讯嫂。里面的prototype就綁定jQuery的原型方法蹦锋。
因此
init.prototype = jQuery.prototype
即
jQuery.prototype.init.prototype = jQuery.fn;
這樣我們就不需要new jQuery,而直接通過(guò)new init()方法欧芽,就可以獲取到j(luò)Query上的原型方法莉掂。
所以
var $ = fucntion jQuery(selector){
return new jQuery.prototype.init(selector)
}
由于prototype太長(zhǎng),也不利于理解千扔,我們用一個(gè)fn表示這些所有的方法憎妙,也就是這個(gè)原型。
因此
jQuery.fn.init.prototype = jQuery.fn;
所以就變成下面這樣了昏鹃。
var $ = fucntion jQuery(){
return new jQuery.fn.init(selector)
}
jQuery.prototype = {
init:function(){}//構(gòu)造函數(shù),
其他方法
}
jQuery.fn = jQuery.prototype
jQuery.fn.init.prototype = jQuery.fn;
$(selector)
總結(jié):
jQuery的巧妙之處在于尚氛,在原型方法jQuery.fn.init
上,返回原構(gòu)造函數(shù)的原型方法jQuery.prototype
,也就是jQuery.fn.init.prototype =jQuery.fn
這樣做的好處一個(gè)是可以獲取到j(luò)Query綁定的原型方法洞渤,一個(gè)是不需要new,因?yàn)槲覀?code>new init時(shí)属瓣,init的原型就可以拿到j(luò)Query的原型了载迄。
以上讯柔,轉(zhuǎn)載請(qǐng)說(shuō)明來(lái)源,謝謝护昧。