原本是想写分析jQuery的部分原理,想一想由于也没有去看过jQuery源码,就改了下标题。dom
出发点很简单,写一个相似jQuery的简化版工具库。ide
准备工做,用$去实例化:函数
function $(domName) { return new obj(domName); }
链式调用并不是是无限延伸,而是调用完就回撤而后再次调用的过程。
因此链式调用的基本原理是 每一个方法都要return this,而且每一个方法调用都是基于this的。
就比如打拳,虽然打出去的动做不同,可是打出去就得收回来,再出拳。工具
出于简化与我的水平缘由,选择器方面,暂时只写了id 和 class类型的this
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等事件原理相似)prototype
obj.prototype.click = function (cb) { this.init.onclick = cb;//节点点击触发回调函数 return this; }
eq选择器,eq是改变this的选择对象(this.init)code
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; }