鏈式調用能讓代碼讀起來像句子:obj.a(1).b(2).c(3)。jQuery 之所以爽快,靠的就是這套機制。下面用兩種思路把它實現出來。
最直觀的做法是讓每個方法執行完畢後返回對象自身。
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;
}
}
調用時就能一路點下去:
var obj = new ClassA();
obj.method1(1).method2(2).method3(3);
// obj -> prop1 = 1, prop2 = 2, prop3 = 3
只要願意,ClassA 有多少方法都能這樣串起來。缺點也很清楚:鏈式能力被硬綁在這一種類型上,每寫一個類都得記得在方法末尾 return this,很容易漏掉。
第二種思路把「鏈」從類剝離出來,做成一個獨立的包裝器 chain。它接收對象,返回一個函數;每次調用這個函數就轉發一次方法調用,並把函數自己返回,於是鏈得以延續。
/**
* 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;
};
}
這時候類的方法體裡不必再返回 this:
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; }
}
調用寫法變成了「函數 + 一串參數列表」:
var obj = new ClassB();
chain(obj)('method1', 4)('method2', 5)('method3', 6);
// obj -> prop1 = 4, prop2 = 5, prop3 = 6
如果鏈的末尾需要拿回對象本身,再補一對空括號即可:
var result = chain(obj)('method1', 4)('method2', 5)('method3', 6)();
// result -> prop1 = 4, prop2 = 5, prop3 = 6
這種寫法的好處是:定義類時方法無須返回 this,而且可以對任意對象啟用鏈式調用,不必預先改造它的原型。
// 寫法一
obj
.method1(arg1)
.method2(arg2)
.method3(arg3)
// 寫法二
chain(obj)
('method1', arg1)
('method2', arg2)
('method3', arg3)
寫法一更貼近 jQuery 的表達習慣,可讀性最好,但需要類主動配合;寫法二侵入性更低,適合在無法修改源頭的對象上「外掛」鏈式能力。
本文的靈感來自 wee 庫,也感謝沐海的分享。