SoFunction
Updated on 2025-04-10

Study on chain calls in JavaScript

1. Object chain: The method returns the object instance itself (this) in the body

Copy the codeThe code is as follows:

function ClassA(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
= {
method1 : function(p1){
this.prop1 = p1;
return this;
},
method2 : function(p2){
this.prop2 = p2;
return this;
},
method3 : function(p3){
this.prop3 = p3;
return this;
}
}

Define function/class ClassA. There are three properties/fields prop1, prop2, and prop3. The three methods method1, method2, and method3 are respectively set to prop1, prop2, and prop3.
The call is as follows:
Copy the codeThe code is as follows:

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

You can see that obj has been operated three times in a row. As long as you are willing to define N methods of ClassA in this way, the call chain will continue.
The disadvantage of this method is that the chain method is uniquely bound to an object type (ClaaaA). In this way, chain operations are implemented. Each class is defined, this must be returned in the body of the method. The second way can solve this problem.
2. Function chain: After the object is passed in, return the function itself.
Copy the codeThe code is as follows:

/**
* chain lite version
* @param {Object} obj
*/
function chain(obj){
return function(){
var Self = ; = obj;
if(==0){
return ;
}
[arguments[0]].apply(,[].(arguments,1));
return Self;
}
}
//Defined function/class ClassB
function ClassB(){
this.prop1 = null;
this.prop2 = null;
this.prop3 = null;
}
= {
method1 : function(p1){
this.prop1 = p1;
},
method2 : function(p2){
this.prop2 = p2;
},
method3 : function(p3){
this.prop3 = p3;
}
}

Note that this will no longer be returned in ClassB's method1, method2, and method3.
The call is as follows:
Copy the codeThe code is as follows:

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

The first method returns the object itself after three calls, and here an empty "()" is used to retrieve the object
Copy the codeThe code is as follows:

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

This method does not need to return this in the method body when writing classes, and any object can be called in a chain.
Two ways of calling:
Copy the codeThe code is as follows:

obj
.method1(arg1)
.method2(arg2)
.method3(arg3)
...
chain(obj)
(method1,arg1)
(method2,arg2)
(method3,arg3)
...

Related:
My function chain evolution