JavaScript中鏈式調用之研習

來源:互聯網
上載者:User

一、對象鏈:方法體內返回對象執行個體自身(this)

複製代碼 代碼如下:function ClassA(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
ClassA.prototype = {
method1 : function(p1){
this.prop1 = p1;
return this;
},
method2 : function(p2){
this.prop2 = p2;
return this;
},
method3 : function(p3){
this.prop3 = p3;
return this;
}
}

定義了function/類ClassA。有三個屬性/欄位prop1,prop2,prop3,三個方法methed1,method2,method3分別設定prop1,prop2,prop3。
調用如下: 複製代碼 代碼如下:var obj = new ClassA();
obj.method1(1).method2(2).method(3); // obj -> prop1=1,prop2=2,prop3=3

可以看到對obj進行了連續三次操作,只要願意ClassA的N多方法都這樣定義,調用鏈會一直延續。
該方式缺點是鏈方法唯一地綁定於一種物件類型(ClaaaA),按這種方式實現鏈式操作,每定義一個類,其方法體中都要返回this。第二種方式可以解決這個問題。
二、函數鏈:對象傳入後每次調用返回函數自身 複製代碼 代碼如下:/**
* chain 精簡版
* @param {Object} obj
*/
function chain(obj){
return function(){
var Self = arguments.callee; Self.obj = obj;
if(arguments.length==0){
return Self.obj;
}
Self.obj[arguments[0]].apply(Self.obj,[].slice.call(arguments,1));
return Self;
}
}
//定義的function/類ClassB
function ClassB(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
ClassB.prototype = {
method1 : function(p1){
this.prop1 = p1;
},
method2 : function(p2){
this.prop2 = p2;
},
method3 : function(p3){
this.prop3 = p3;
}
}

注意ClassB的method1,method2,method3中不再返回this了。
調用如下: 複製代碼 代碼如下:var obj = new ClassB();
chain(obj)('method1',4)('method2',5)('method3',6); // obj -> prop1=4,prop2=5,prop3=6

第一種方式3次調用後返回了對象自身,這裡使用一個空"()"取回對象 複製代碼 代碼如下:// result -> prop1=4,prop2=5,prop3=6
var result = chain(obj)('method1',4)('method2',5)('method3',6)();

這種方式寫類時方法體中無須返回this,且可以對任何對象進行鏈式調用。
兩種的調用方式: 複製代碼 代碼如下:obj
.method1(arg1)
.method2(arg2)
.method3(arg3)
...
chain(obj)
(method1,arg1)
(method2,arg2)
(method3,arg3)
...

相關:
我的函數鏈之演變

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.