Let's look at an example of this to see how it works. Here's a section of the code where we define an object and then run several methods on the object.
var newB = new example(); newB.firstMethod('x'); newB.secondMethod('y'); newB.thirdMethod(1,15,'z');
As you can see from the code none of the values returned from any of out three methods are actually being used since none of them have the returned value assigned to anything. Quite probably the way you currently have these methods defined you don't have them returning anything at all. We are going to change that.
What we need to do with all these methods that do not currently return anything is to add one extra line of code to the end of each of the methods.
With that line of code in place our methods now each return the object that they belong to This is the only change that we need to make to methods in order to allow us to use method chaining. Of course we can't add that line if the method already returns a value but them methods that return values are not suited to method chaining in the first place as each of those needs to be specified separately in order to be able to assign the value that is returned.
With our methods that don't normally need to return a value now returning a reference to the object that they belong to it is no longer necessary for us to use three separate statements to call those three methods. We can now combine all three into one statement simply by chaining the methods together.
var newB = new example(); newB.firstMethod('x').secondMethod('y').thirdMethod(1,15,'z');
This works because the last statement in firstMethod() is return this; which in this case returns a reference to newB. This means that newB.firstMethod() after the method has run is equivalent to newB and so can be substituted for newB where we want the method to be run and the object to be available for further referencing.
- Extending Built In Objects
- Creating Objects from Existing Objects
- Creating New Objects Without Copying Existing Ones
- Dot Notation and "this"
- Inheritance and "constructor"
- Associative Array Notation
- Create Method if Doesn't Exist
- "self" and Multiple Objects
- Defining Objects with JSON
- Lazy Definition
- Extending Methods
- Copying Objects
- Private Properties and Privileged Methods
- Public Access to Private Methods
- Chaining Methods