學(xué)習(xí)JavaScript設(shè)計(jì)模式(鏈?zhǔn)秸{(diào)用)
1、什么是鏈?zhǔn)秸{(diào)用
這個(gè)很容易理解,例如:
$(this).setStyle('color', 'red').show();
一般的函數(shù)調(diào)用和鏈?zhǔn)秸{(diào)用的區(qū)別:調(diào)用完方法后,return this返回當(dāng)前調(diào)用方法的對(duì)象。
function Dog(){ this.run= function(){ alert("The dog is running...."); return this;//返回當(dāng)前對(duì)象 Dog }; this.eat= function(){ alert("After running the dog is eatting...."); return this;//返回當(dāng)前對(duì)象 Dog }; this.sleep= function(){ alert("After eatting the dog is running...."); return this;//返回當(dāng)前對(duì)象 Dog }; } //一般的調(diào)用方式; /* var dog1 =new Dog(); dog1.run(); dog1.eat(); dog1.sleep();*/ var dog2 = new Dog(); dog2.run().eat().sleep();
2、分解鏈?zhǔn)秸{(diào)用
鏈?zhǔn)秸{(diào)用其實(shí)是兩個(gè)部分:
1).操作對(duì)象(也就是被操作的DOM元素,如上例的$(this))
2).操作方法(具體要做什么事情,如上例的setStyle和show)
如何實(shí)現(xiàn)操作對(duì)象與操作方法
創(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; }
但是,如果把這個(gè)函數(shù)改造為一個(gè)構(gòu)造器,把那些元素作為數(shù)組保存在一個(gè)實(shí)例屬性中,并讓所有定義在構(gòu)造器函數(shù)的prototype屬性所指對(duì)象中的方法都返回用以調(diào)用方法的那個(gè)實(shí)例的引用,那么它就具有了鏈?zhǔn)秸{(diào)用的能力。(說了這么多,就是在每個(gè)方法最后return this;),
我首先需要把這個(gè)$函數(shù)改為一個(gè)工廠方法,它負(fù)責(zé)創(chuàng)建支持鏈?zhǔn)秸{(diào)用的對(duì)象。這個(gè)函數(shù)應(yīng)該能接受元素?cái)?shù)組形式的參數(shù),以便我們能夠使用與原來一樣的公用接口。這樣以來,它就具有了進(jìn)行鏈?zhǔn)秸{(diào)用的能力。
改造后如下:
(function(){ function _$(els){ this.elements = [];//把那些元素作為數(shù)組保存在一個(gè)實(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; //在每個(gè)方法的最后return this; }, setStyle: function(prop, val){ this.each(function(el){ el.style[prop] = val; }); return this; //在每個(gè)方法的最后return this; }, show: function(){ var that = this; this.each(function(el){ that.setStyle('display', 'block'); }); return this; //在每個(gè)方法的最后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; //在每個(gè)方法的最后return this; } } window.$ = function(){ return new _$(arguments); } })();
在最后return this,這就將調(diào)用方法的對(duì)象傳給調(diào)用鏈上的下一個(gè)方法。
3、模擬jquery底層鏈?zhǔn)骄幊?/strong>
// 塊級(jí)作用域 //特點(diǎn)1 程序啟動(dòng)的時(shí)候 里面的代碼直接執(zhí)行了 //特點(diǎn)2 內(nèi)部的成員變量 外部無法去訪問 (除了不加var修飾的變量) (function(window , undefined){ // $ 最常用的對(duì)象 返回給外界 大型程序開發(fā) 一般使用'_'作為私用的對(duì)象(規(guī)范) function _$(arguments){ //實(shí)現(xiàn)代碼...這里僅實(shí)現(xiàn)ID選擇器 // 正則表達(dá)式匹配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類上擴(kuò)展一個(gè)可以實(shí)現(xiàn)鏈?zhǔn)骄幊痰姆椒? Function.prototype.method = function(methodName , fn){ this.prototype[methodName] = fn ; return this ; //鏈?zhǔn)骄幊痰年P(guān)鍵 } // 在_$的原型對(duì)象上 加一些公共的方法 _$.prototype = { constructor : _$ , addEvent:function(type,fn){ // 給你的得到的元素 注冊(cè)事件 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 上先注冊(cè)一個(gè)全局變量 與外界產(chǎn)生關(guān)系 window.$ = _$ ; // 寫一個(gè)準(zhǔn)備的方法 _$.onReady = function(fn){ // 1 實(shí)例化出來_$對(duì)象 真正的注冊(cè)到window上 window.$ = function(){ return new _$(arguments); }; // 2 執(zhí)行傳入進(jìn)來的代碼 fn(); // 3 實(shí)現(xiàn)鏈?zhǔ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('我被點(diǎn)擊了!'); }).setStyle('backgroundColor' , 'red'); });
4、使用回調(diào)函數(shù)從支持鏈?zhǔn)秸{(diào)用的方法獲取數(shù)據(jù)
鏈?zhǔn)秸{(diào)用很適合于賦值器方法,但對(duì)于取值器方法,就不方便了,因?yàn)槊總€(gè)方法返回的都是this啊。
不過,變通的方法還是有的,那就是回調(diào)函數(shù)。
未使用回調(diào)函數(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());
使用回調(diào)函數(shù)時(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);
在使用回調(diào)函數(shù)時(shí)候callback.call(this, name)在一般情況下是沒問題的,但是,這個(gè)例子偏偏用到了console.log,那么就有問題了。原因是console的this是指向console而不是winodw。
這個(gè)問題也很好解決。如下:
//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);
鏈?zhǔn)秸{(diào)用這種風(fēng)格有助于簡(jiǎn)化代碼的編寫工作,讓代碼更加簡(jiǎn)潔、易讀,同時(shí)也避免多次重復(fù)使用一個(gè)對(duì)象變量,希望大家可以熟練掌握。
- 原生js封裝的一些jquery方法(詳解)
- 原生js仿jquery實(shí)現(xiàn)對(duì)Ajax的封裝
- 詳解JavaScript原生封裝ajax請(qǐng)求和Jquery中的ajax請(qǐng)求
- JavaScript使用鏈?zhǔn)椒椒ǚ庋bjQuery中CSS()方法示例
- 原生js實(shí)現(xiàn)對(duì)Ajax的封裝(仿jquery)
- 基于jquery封裝的一個(gè)js分頁
- JS鏈?zhǔn)秸{(diào)用的實(shí)現(xiàn)方法
- 原生js實(shí)現(xiàn)簡(jiǎn)單的鏈?zhǔn)讲僮?/a>
- javascript中的鏈?zhǔn)秸{(diào)用
- js實(shí)現(xiàn)封裝jQuery的簡(jiǎn)單方法與鏈?zhǔn)讲僮髟斀?/a>
相關(guān)文章
JS實(shí)現(xiàn)IE狀態(tài)欄文字縮放效果代碼
這篇文章主要介紹了JS實(shí)現(xiàn)IE狀態(tài)欄文字縮放效果代碼,涉及JavaScript針對(duì)瀏覽器的相關(guān)調(diào)用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10JavaScript本地?cái)?shù)據(jù)存儲(chǔ)sessionStorage與localStorage使用詳解
這篇文章主要介紹了JavaScript本地?cái)?shù)據(jù)存儲(chǔ)sessionStorage與localStorage使用,localStorage:永久存儲(chǔ)在本地,適合保存在本地的數(shù)據(jù)。sessionStorage:會(huì)話級(jí)的存儲(chǔ),敏感帳號(hào)一次登陸2022-10-10BootStrap 下拉菜單點(diǎn)擊之后不會(huì)出現(xiàn)下拉菜單(下拉菜單不彈出)的解決方案
最近學(xué)到Bootstrap下拉菜單,學(xué)懂了教程內(nèi)容之后自己敲一個(gè)點(diǎn)擊按鈕底下彈出下拉菜單的小demo,寫完代碼發(fā)現(xiàn)運(yùn)行之后點(diǎn)擊按鈕沒反應(yīng),下拉菜單彈不出來,下面給大家分享下解決方案2016-12-12JS動(dòng)態(tài)獲取當(dāng)前時(shí)間,并寫到特定的區(qū)域
JS動(dòng)態(tài)獲取當(dāng)前時(shí)間,并寫到特定的區(qū)域,需要的朋友可以參考一下2013-05-05