浅层次分析链式调用的部分原理
文章目录
本来是想写分析jQuery的部分原理,想想因为也没有去看过jQuery源码,就改了下标题。
出发点很简单,写一个类似jQuery的简化版工具库。
准备工作,用$去实例化:
function $(domName) {
return new obj(domName);
}
链式调用并非是无限延伸,而是调用完就回撤然后再次调用的过程。
所以链式调用的基本原理是 每个方法都要return this,并且每个方法调用都是基于this的。
就好比打拳,虽然打出去的动作不一样,但是打出去就得收回来,再出拳。
出于简化与个人水平原因,选择器方面,暂时只写了id 和 class类型的
function obj(domName) {
if (String(domName)[0] === '#') {
this.total = 'singular';//表示选择器获得节点为单数,调用其他方法的时候无需循环
this.init = document.getElementById(new String(domName).substring(1,new String(domName).length));//获取节点
}else if(String(domName)[0] === '.'){
this.total = 'majority';//表示选择器获得节点为多数,调用其他方法的时候需要循环
this.init = document.getElementsByClassName(new String(domName).substring(1,new String(domName).length));//获取节点
}
this.length = this.init.length;
}
click事件(change,mouseover等事件原理类似)
obj.prototype.click = function (cb) {
this.init.onclick = cb;//节点点击触发回调函数
return this;
}
eq选择器,eq是改变this的选择对象(this.init)
obj.prototype.eq= function (index) {
this.init = this.init[index];
this.total = 'singular';//改变选择节点的数目类型
return this;
}
hide(show需要获取一下之前的display。。。相比较hide复杂一些)
obj.prototype.hide = function () {
if (this.total === 'majority') {//选择的节点为多数需要循环
for(let i = 0; i < this.init.length; i ++) {
this.init[i].style.display = 'none';
}
}else if( this.total === 'singular'){
this.init.style.display = 'none';
}
return this;
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论