本文實例分析了JavaScript鏈式調用。分享給大家供大家參考,具體如下:
對$
函數你已經很熟悉了。它通常返回一個html元素或一個html元素的集合,如下:
function$(){ var elements = []; for(vari=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;}
但是,如果把這個函數改造為一個構造器,把那些元素作為數組保存在一個實例屬性中,并讓所有定義在構造器函數的prototype
屬性所指對象中的方法都返回用以調用方法的那個實例的引用,那么它就具有了鏈式調用的能力。我首先需要把這個$
函數改為一個工廠方法,它負責創建支持鏈式調用的對象。這個函數應該能接受元素數組形式的參數,以便我們能夠使用與原來一樣的公用接口。
(function(){ //use private class function _$(els){ this.elements = []; for(vari=0,len=els.length;i<len;i++){ var element = els[i]; if(typeof element ===”string”){ element = document.getElementById(element); } this.elements.push(element) } } //The public interface remains the same. window.$ = function(){ return new _$(arguments); }})();
由于所有對象都會繼承其原型對象的屬性和方法,所以我們可以讓定義在原型對象中的那幾個方法都返回用以調用方法的實例對象的引用,這樣就可以對那些方法進行鏈式調用。想好這一點,我們現在就動手在_$
這個私用構造函數的prototype
對象中添加方法,以便實現鏈式調用
(function(){ //use private class function _$(els){ //..省略之前上面的代碼 } _$.prototype = { each:function(fn){ for(var i=0,len=this.elements.length;i<len;i++){ fn.call(this,this.elements[i]); } return this; }, show:function(prop,val){ var that = this; this.each(function(el){ that.setStyle("display”,”block"); }); return this; }, addEvent:function(type,fn){ var add = function(el){ if(window.addEventListener){ el.addEventListener(type,fn,false); }else if(window.attachEvent){ el.attachEvent("on"+type,fn); } }; this.each(function(el){ add(el); }); return this; } }; //The public interface remains the same. window.$ = function(){ return new _$(arguments); }})();
但是如果某個庫或者框架已經定義了一個$
函數,那么我們的這個庫會將其改寫,有個簡單的辦法是在源碼中為$
函數另去一個名字。但是如果你是從一個現有的庫獲得的源碼,那么每次代碼庫獲取更新的版本后 你都得重新改名字,因此這個方案并不是很好。好的解決辦法就是像下面一樣添加一個安裝器:
window.installHelper = function(scope, interface) { scope[interface] = function() { return new _$(arguments); } };
用戶可以這樣去使用:
installHelper(window, '$');$('example').show();
下面是一個更復雜的例子,它展示了如何把這種功能添加到一個事先定義好的命名對象中:
// Define a namespace without overwriting it if it already exists.window.com = window.com || {};com.example = com.example || {};com.example.util = com.example.util || {};installHelper(com.example.util, 'get');(function() { var get = com.example.util.get; get('example').addEvent('click', function(e) { get(this).addClass('hello'); });})();
有時候把方法連起來并不是一個好主意。鏈式調用很適合于賦值器方法,但對于取值器的方法,你可能會希望他們返回你要的數據而不是返回this
。不過,如果你把鏈式調用作為首要目標,希望所有方法的使用方式保持一致的話,那么變通的方法還是有的:你可以利用回調技術來返回所要的數據下面有兩個例子:其中API類使用了普通的取值器(它中斷了調用鏈),而API2類則使用了回調方法:
// Accessor without function callbacks: returning requested data in accessors.window.API = window.API || {};API.prototype = function() { var name = 'Hello world'; // Privileged mutator method. setName: function(newName) { name = newName; return this; }, // Privileged accessor method. getName: function() { return name; }}();// Implementation code.var o = new API;console.log(o.getName()); // Displays 'Hello world'.console.log(o.setName('Meow').getName()); // Displays 'Meow'.// Accessor with function callbacks.window.API2 = window.API2 || {};API2.prototype = function() { var name = 'Hello world'; // Privileged mutator method. setName: function(newName) { name = newName; return this; }, // Privileged accessor method. //通過把函數作為參數傳入 getName: function(callback) { callback.call(this, name); return this; }}();// Implementation code.var o2 = new API2;o2.getName(console.log).setName('Meow').getName(console.log);// Displays 'Hello world' and then 'Meow'.
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答