DIV CSS 佈局教程網

JavaScript 鏈式呼叫之研習:物件鏈與函式鏈對比
編輯:關於JavaScript     

鏈式呼叫(如 jQuery 的 .method1().method2())讓程式碼讀起來如流水般順暢。它的實現其實有兩種主要思路:物件鏈與函式鏈。以下分別說明並比較。

一、物件鏈:方法體內返回 this

最直觀的做法,是讓每個方法在執行完後回傳物件實例自身(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; }
}

呼叫時便能一路串下去:

var obj = new ClassA();
obj.method1(1).method2(2).method3(3); // obj -> prop1=1, prop2=2, prop3=3

可以看到對 obj 連續做了三次操作,只要願意,ClassA 的眾多方法都能這樣串接。

缺點:這種方式的鏈方法唯一地綁定於某種物件類型(ClassA),每定義一個類別,其方法體中都得返回 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 的三個方法中不再返回 this 了。呼叫時改透過 chain 包裝:

var obj = new ClassB();
chain(obj)('method1', 4)('method2', 5)('method3', 6); // obj -> prop1=4, prop2=5, prop3=6

第一種方式在三次呼叫後返回了物件自身,這裡則使用一個空 () 來取回物件:

// 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)
...

相關:我的函式鏈之演變

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved