最简版的jQuery原理解析

网上很多jQuery的分析文章,虽然很详细,但是对我这种小白,只想了解一下大概原理,而不想花太多时间研究细节,于是我就抽出jQuery绑定元素及方法的核心思想,没有图,但是相信你一定能看懂。

我们想要$('selector')时就获得一个元素,且里面有一些方法。
这些方法要绑定在原型prototype上。

所以jQuery必须是个构造函数

var $ = new fucntion jQuery(){}

假设里面有个方法是绑定元素的,叫做init,我们首先要在prototype绑定这个方法。

jQuery.prototype.init = function(){}

当然jQuery里还有其他实例方法,比如each方法,那我们需要这样写。

jQuery.prototype = {
    init: function(){},
    each: function(callback, args) {},
    其他方法...
}

然后我们需要返回这个元素,因此返回的是init方法的执行结果.

var $ = new fucntion jQuery(){ 
    return  jQuery.prototy.init(selector)
}

但是我们返回的是init创造的dom,因此我们也要在init里获取到jquery的原型上的方法,因此最好的办法是把init函数也当成一个构造函数。里面的prototype就绑定jQuery的原型方法。

因此

init.prototype = jQuery.prototype 

jQuery.prototype.init.prototype = jQuery.fn;

这样我们就不需要new jQuery,而直接通过new init()方法,就可以获取到jQuery上的原型方法。

所以

var $ = fucntion jQuery(selector){
    return new jQuery.prototype.init(selector)
}

由于prototype太长,也不利于理解,我们用一个fn表示这些所有的方法,也就是这个原型。
因此

jQuery.fn.init.prototype = jQuery.fn;

所以就变成下面这样了。

var $ = fucntion jQuery(){ 
    return  new jQuery.fn.init(selector)
}

jQuery.prototype = {
    init:function(){}//构造函数,
    其他方法
}

jQuery.fn = jQuery.prototype

jQuery.fn.init.prototype = jQuery.fn;

$(selector)

以上,转载请说明来源,谢谢。

    原文作者:铁腕阿童木
    原文地址: https://segmentfault.com/a/1190000013495290
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞