方法的链式调用(MethodChaining)

链式调用出现在一些类库中,比较典型的就是jQuery的链式API:

$(':header').map(function(){return this.id;}).get().sort()

MethodChaining这个术语最早出现于Martin Fowler大大的博文:https://martinfowler.com/dslwip/MethodChaining.html。

通常,可以在一个方法内通过返回调用上下文进行链式调用:

var obj={
    // 方法一
    f1:function(){
       return this;
    },
    // 方法二
    f2:function(){
       return this;
    },
    // 方法三
   f3:function(){
       console.log(3);
   }
};

obj.f1().f2().f3();    // 3

于是我突然受此启发:这样不就可以完成一系列动作了吗:

var obj={
    f1:function(a){
        console.log(a);    // 动作一
        return this;
    },
    f2:function(b){
        console.log(b);    // 动作二
        return this;
    },
    f3:function(c){
         console.log(c);   // 动作三
    }
}; 

obj.f1(1).f2(2).f3(3);     // 1 2 3

通过返回调用方法的对象,就可以实现链式调用,这个过程只需要指定一次要调用的对象即可,而且能够实现一系列连续的动作(如上面一连续输出1 2 3),十分方便。


 

posted @ 2018-03-10 16:41  linweiws  阅读(228)  评论(0编辑  收藏  举报