原本是想寫分析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; }