JavaScript中链式调用之研习

方法链一般适合对一个对象进行连续操作(集中在一句代码)。一定程度上可以减少代码量,缺点是它占用了函数的返回值。

 

一、对象链:方法体内返回对象实例自身(this)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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。
调用如下:

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


可以看到对obj进行了连续三次操作,只要愿意ClassA的N多方法都这样定义,调用链会一直延续。

该方式缺点是链方法唯一地绑定于一种对象类型(ClaaaA),按这种方式实现链式操作,每定义一个类,其方法体中都要返回this。第二种方式可以解决这个问题。

 

二、函数链:对象传入后每次调用返回函数自身

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * chain 精简版
 * @param {Object} obj
 */
function chain(obj) {
    var slice = [].slice
    return function() {
        var Self = arguments.callee
        var 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了。
调用如下:

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


第一种方式3次调用后返回了对象自身,这里使用一个空"()"取回对象

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

这种方式写类时方法体中无须返回this,且可以对任何对象进行链式调用。

两种的调用方式:

1
2
3
4
5
6
7
8
9
10
11
obj
    .method1(arg1)
    .method2(arg2)
    .method3(arg3)
    ...
     
chain(obj)
    (method1,arg1)
    (method2,arg2)
    (method3,arg3)
    ...

 

相关:

我的函数链之演变 

posted on   snandy  阅读(5104)  评论(6编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
< 2011年4月 >
27 28 29 30 31 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
1 2 3 4 5 6 7

统计

点击右上角即可分享
微信分享提示