1. Object chain: the method body returns the object instance itself (this)
Copy codeThe Code is as follows:
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;
}
}
Defines the function/class ClassA. There are three attributes/fields: prop1, prop2, prop3, and the three methods methed1, method2, and method3 respectively set prop1, prop2, and prop3.
The call is as follows:
Copy 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 is operated three times in a row. As long as you want to define N methods of ClassA, 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, the chain operation is implemented. this is returned in the method body for each class defined. The second method can solve this problem.
Ii. Function chain: After an object is passed in, each call returns the function itself.
Copy codeThe Code is as follows:
/**
* Chain Lite version
* @ 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;
}
}
// Defined function/class 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;
}
}
Note that this is no longer returned in method1, method2, and method3 of ClassB.
The call is as follows:
Copy 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. Here, an empty "()" is used to retrieve the object.
Copy codeThe Code is as follows:
// Result-> prop1 = 4, prop2 = 5, prop3 = 6
Var result = chain (obj) ('method1 ', 4) ('method2', 5) ('method3 ', 6 )();
When writing a class in this way, the method body does not need to return this, and any object can be called in a chain.
Two call methods:
Copy codeThe Code is as follows:
Obj
. Method1 (arg1)
. Method2 (arg2)
. Method3 (arg3)
...
Chain (obj)
(Method1, arg1)
(Method2, arg2)
(Method3, arg3)
...
Related:
Evolution of my function chain