Method 1:
Why don't we create infinite chainability using prototypal inheritance, and create the possibility to pass in as many arguments as we want using the automatically created arguments array?
I'll present the simplified version. You can also create a pretty wrapper for all this, and return the wrapper to the world... the window, like on this page.
Take note, that you must use the new keyword with test... otherwise all of the this keywords will end up referring simply to the window.......... which isn't all that useful.
So, each instance of this object does 2 things:
You can chain all the methods as much as you want. This is achieved by the use of return this;
It keeps track of all the arguments passed in with this.args.
Example:
new test("p1", "p2").example("p3").example("p4", "p5").showAll("p6", "p7", "p8");
// Output:
// The params are: p1, p2, p3, p4, p5, p6, p7, p8
The Code:
(function(){ // <== Let's not pollute the global namespace.
function test() { // <== The constructor
// Must copy arguments, since they're read only
this.args = [];
this.addArgs(arguments);
}
// Add some methods:
test.prototype = {
example : function() {
// Add on new arguments
this.addArgs(arguments);
// Return the instance for chainability
return this;
},
showAll : function() {
var i, string = "The params are: ";
// Add on new arguments
this.addArgs(arguments);
// show all arguments
alert(string + this.args.join(", "));
return this;
},
addArgs: function(array) {
var i;
for (i = 0; i < array.length; ++i)
{ this.args.push(array[i]); }
return this;
}
};
new test("p1","p2").example("p3").example("p4","p5").showAll("p6","p7","p8");
})();
Method 2:
This method is probably not quite as useful as the first when written like this, but makes better use of the classless nature of JS. It can be tweaked to be very useful in some situations. The trick is that in properties of an object, this refers to the object. In this case you don't have to use the new keyword, and you still get chainability, but the format becomes slightly different.... You essentially refer to Tdirectly.
Anyway, it's just an alternate method of creating chainability by using return this;:
(function(){ // <== Let's not pollute the global namespace.
var T = {}; // "this" will be T in the properties / methods of T
T.args = [];
T.example = function() {
var i;
for (i = 0; i < arguments.length; ++i)
{ this.args.push(arguments[i]); }
return this; // <== Chainability
};
T.show = function() {
alert(this.args.join(","));
return this;
}
// Let's try it out:
T.example("a", "b").example("c").show();
// Output: a, b, c
})();
jsFiddle example