學習JavaScript設計模式(鏈式調用)
1、什么是鏈式調用
這個很容易理解,例如:
$(this).setStyle('color', 'red').show();
一般的函數(shù)調用和鏈式調用的區(qū)別:調用完方法后,return this返回當前調用方法的對象。
function Dog(){ this.run= function(){ alert("The dog is running...."); return this;//返回當前對象 Dog }; this.eat= function(){ alert("After running the dog is eatting...."); return this;//返回當前對象 Dog }; this.sleep= function(){ alert("After eatting the dog is running...."); return this;//返回當前對象 Dog }; } //一般的調用方式; /* var dog1 =new Dog(); dog1.run(); dog1.eat(); dog1.sleep();*/ var dog2 = new Dog(); dog2.run().eat().sleep();
2、分解鏈式調用
鏈式調用其實是兩個部分:
1).操作對象(也就是被操作的DOM元素,如上例的$(this))
2).操作方法(具體要做什么事情,如上例的setStyle和show)
如何實現(xiàn)操作對象與操作方法
創(chuàng)建一般的$函數(shù):
function $(){ var elements = []; for(var i= 0,len=arguments.length; i<len; i++){ var element = arguments[i]; if(typeof element==='string'){ element = document.getElementById(element); } if(arguments.length==1){ return element; } elements.push(element); } return elements; }
但是,如果把這個函數(shù)改造為一個構造器,把那些元素作為數(shù)組保存在一個實例屬性中,并讓所有定義在構造器函數(shù)的prototype屬性所指對象中的方法都返回用以調用方法的那個實例的引用,那么它就具有了鏈式調用的能力。(說了這么多,就是在每個方法最后return this;),
我首先需要把這個$函數(shù)改為一個工廠方法,它負責創(chuàng)建支持鏈式調用的對象。這個函數(shù)應該能接受元素數(shù)組形式的參數(shù),以便我們能夠使用與原來一樣的公用接口。這樣以來,它就具有了進行鏈式調用的能力。
改造后如下:
(function(){ function _$(els){ this.elements = [];//把那些元素作為數(shù)組保存在一個實例屬性中, for(var i= 0, len=els.length; i<len; i++){ var element = els[i]; if(typeof element==='string'){ element = document.getElementById(element); } this.elements.push(element); } } _$.prototype = { each: function(fn){ for(var i= 0,len=this.elements.length; i<len; i++){ fn.call(this, this.elements[i]); } return this; //在每個方法的最后return this; }, setStyle: function(prop, val){ this.each(function(el){ el.style[prop] = val; }); return this; //在每個方法的最后return this; }, show: function(){ var that = this; this.each(function(el){ that.setStyle('display', 'block'); }); return this; //在每個方法的最后return this; }, addEvent: function(type, fn){ var add = function(el){ if(window.addEventListener){ el.addEventListener(type, fn, false); }else if(window.attachEvent){ el.addEvent('on'+type, fn); } }; this.each(function(el){ add(el); }); return this; //在每個方法的最后return this; } } window.$ = function(){ return new _$(arguments); } })();
在最后return this,這就將調用方法的對象傳給調用鏈上的下一個方法。
3、模擬jquery底層鏈式編程
// 塊級作用域 //特點1 程序啟動的時候 里面的代碼直接執(zhí)行了 //特點2 內部的成員變量 外部無法去訪問 (除了不加var修飾的變量) (function(window , undefined){ // $ 最常用的對象 返回給外界 大型程序開發(fā) 一般使用'_'作為私用的對象(規(guī)范) function _$(arguments){ //實現(xiàn)代碼...這里僅實現(xiàn)ID選擇器 // 正則表達式匹配id選擇器 var idselector = /#\w+/ ; this.dom ; // 此屬性 接受所得到的元素 // 如果匹配成功 則接受dom元素 arguments[0] = '#inp' if(idselector.test(arguments[0])){ this.dom = document.getElementById(arguments[0].substring(1)); } else { throw new Error(' arguments is error !'); } }; // 在Function類上擴展一個可以實現(xiàn)鏈式編程的方法 Function.prototype.method = function(methodName , fn){ this.prototype[methodName] = fn ; return this ; //鏈式編程的關鍵 } // 在_$的原型對象上 加一些公共的方法 _$.prototype = { constructor : _$ , addEvent:function(type,fn){ // 給你的得到的元素 注冊事件 if(window.addEventListener){// FF this.dom.addEventListener(type , fn); } else if (window.attachEvent){// IE this.dom.attachEvent('on'+type , fn); } return this ; }, setStyle:function(prop , val){ this.dom.style[prop] = val ; return this ; } }; // window 上先注冊一個全局變量 與外界產(chǎn)生關系 window.$ = _$ ; // 寫一個準備的方法 _$.onReady = function(fn){ // 1 實例化出來_$對象 真正的注冊到window上 window.$ = function(){ return new _$(arguments); }; // 2 執(zhí)行傳入進來的代碼 fn(); // 3 實現(xiàn)鏈式編程 _$.method('addEvent',function(){ // nothing to do }).method('setStyle',function(){ // nothing to do }); }; })(window); // 程序的入口 window傳入作用域中 $.onReady(function(){ var inp = $('#inp'); //alert(inp.dom.nodeName); //alert($('#inp')); inp.addEvent('click',function(){ alert('我被點擊了!'); }).setStyle('backgroundColor' , 'red'); });
4、使用回調函數(shù)從支持鏈式調用的方法獲取數(shù)據(jù)
鏈式調用很適合于賦值器方法,但對于取值器方法,就不方便了,因為每個方法返回的都是this啊。
不過,變通的方法還是有的,那就是回調函數(shù)。
未使用回調函數(shù)時
//without callback window.API = window.API || function(){ var name = 'JChen'; this.setName = function(newName){ name = newName; return this; }; this.getName = function(){ return name; }; }; var o = new API(); console.log(o.getName()); console.log(o.setName('Haha').getName());
使用回調函數(shù)時
//with callback window.API2 = window.API2 || function(){ var name = 'JChen'; this.setName = function(newName){ name = newName; return this; }; this.getName = function(callback){ callback.call(this, name); return this; }; }; var o2 = new API2(); o2.getName(console.log).setName('Hehe').getName(console.log);
在使用回調函數(shù)時候callback.call(this, name)在一般情況下是沒問題的,但是,這個例子偏偏用到了console.log,那么就有問題了。原因是console的this是指向console而不是winodw。
這個問題也很好解決。如下:
//with callback window.API2 = window.API2 || function(){ var name = 'JChen'; this.setName = function(newName){ name = newName; return this; }; this.getName = function(callback){ callback.call(this, name); return this; }; }; var o2 = new API2(); var log = function(para){ console.log(para); }; o2.getName(log).setName('Hehe').getName(log);
鏈式調用這種風格有助于簡化代碼的編寫工作,讓代碼更加簡潔、易讀,同時也避免多次重復使用一個對象變量,希望大家可以熟練掌握。
相關文章
JavaScript本地數(shù)據(jù)存儲sessionStorage與localStorage使用詳解
這篇文章主要介紹了JavaScript本地數(shù)據(jù)存儲sessionStorage與localStorage使用,localStorage:永久存儲在本地,適合保存在本地的數(shù)據(jù)。sessionStorage:會話級的存儲,敏感帳號一次登陸2022-10-10BootStrap 下拉菜單點擊之后不會出現(xiàn)下拉菜單(下拉菜單不彈出)的解決方案
最近學到Bootstrap下拉菜單,學懂了教程內容之后自己敲一個點擊按鈕底下彈出下拉菜單的小demo,寫完代碼發(fā)現(xiàn)運行之后點擊按鈕沒反應,下拉菜單彈不出來,下面給大家分享下解決方案2016-12-12