One, the method body returns the object instance itself (this)
Copy Code code 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 property/field Prop1,prop2,prop3, three methods methed1,method2,method3 set PROP1,PROP2,PROP3 respectively.
Chained calls are as follows:
Copy Code code as follows:
var obj = new ClassA ();
OBJ.METHOD1 (1). METHOD2 (2). Method (3); Obj-> prop1=1,prop2=2,prop3=3
You can see that you have three consecutive operations on obj, and the call chain continues as long as you are willing to ClassA the N multiple methods.
The disadvantage of this approach is that the chain method is uniquely bound to an object type (CLAAAA), which implements chained operations in this way, each defining a class that is returned in its method body. The second way to solve this problem.
second, after the object is passed in each call returns the function itself
Copy Code code as follows:
/**
* Chain Compact 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 the method1,method2,method3 of CLASSB.
Chained calls are as follows:
Copy Code code 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 3 calls, using a null "()" to retrieve the object
Copy Code code as follows:
Result-> prop1=4,prop2=5,prop3=6
var result = Chain (obj) (' Method1 ', 4) (' Method2 ', 5) (' Method3 ', 6) ();
This way, when writing a class, you do not need to return this in the body of the method, and you can make a chained call to any object.
From the writing to summarize the following two types of invocation:
Copy Code code as follows:
Obj
. METHOD1 (ARG1)
. METHOD2 (ARG2)
. METHOD3 (ARG3)
...
Chain (obj)
(METHOD1,ARG1)
(METHOD2,ARG2)
(METHOD3,ARG3)
...
Finally, thank Mu Hai, I was from the Wee Library to get the above inspiration.
/201101/yuanma/chain.rar