This is related to a question I asked previously here: How to implement chained method calls like jQuery?
I have been using the method from the check answer from some time there, and it works well. But I would like to alter the syntax for my toolkit even further.
-
foo(firstarg).bar(secondarg); // should function as the question above. -
foo(onlyarg).bar // a function with one argument -
foo.bar(onlyarg); // should also work, when a first argument is not appropriate. -
foo.bar; // a function without an argument, or returns a static value.
I would like all 4 syntaxs to work off the same foo object, but lack the OOP understanding to do so. I have tried a few things, and so far I can get 1 & 2 to work, and 3 & 4 to work, but not to all work together. It also would be nice if chaining remained an option by having each function return the root object.
Edit: I clearly need to be more specific, here is what I have now:
var main = function(obj){ this.obj = obj; };
var tool = function(obj){ return new main(obj); };
main.prototype = {
alertThisPlus : function(plus){
alert(this.obj + ' ' + plus);
},
alertJustThis : function(){
return alert(this.obj);
}
};
usage
tool('hello').alertThisPlus('world'); // returns alert('hello world')
tool().alertJustThis('hello world'); // returns alert('hello world');
what I would like is to do this:
tool('hello').alertThisPlus('world'); // returns alert('hello world') no change
tool.alertJustThis('hello world'); // returns alert('hello world') does not work
Functions are just objects so you can add functions to ‘tool’. You can do this manually:
Or if your classes are structured suitably you could use a mix-in approach. Something like this: