DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Function Overloader //JavaScript Class

11.02.2005
| 9395 views |
  • submit to reddit
        <a href="http://jsfromhell.com/classes/overloader">
This class allows javascript functions to be overloaded.

[UPDATED CODE AND HELP CAN BE FOUND HERE]
</a>



Usage:

myFunction = new Overloader;

myFunction.overload(function(x){
	document.write("Receives: NUMBER<br />");
}, Number);

myFunction.overload(function(x){
	document.write("Receives: STRING<br />");
}, String);

myFunction.overload(function(x,y){
	document.write("Receives: FUNCTION, NUMBER<br />");
}, Function, Number);

myFunction.overload(function(x,y){
	document.write("Receives: NUMBER, STRING<br />");
}, Number, String);

//test...
myFunction(function(){}, 123); //function + number version
myFunction(123); //number version
myFunction("ABC"); //string version
myFunction(123, "ABC"); //number + string version
myFunction({}); /*There's no Object version, so the function will choose the one that has more arguments in common and if there isnt a "best match", it will use the first function that was overloaded...*/


Here's the code

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/overloader [v1.0]

Overloader = function(){ //v1.0
	var f = function(args){
		var i, h = "#";
		for(i in args = [].slice.call(arguments))
			h += args[i].constructor;
		if(!(h = f._methods[h])){
			var x, j, k, m = -1;
			for(i in f._methods){
				for(j in args.length > (k = 0, x = f._methods[i][1]).length ? x : args)
					(args[j] instanceof x[j] || args[j].constructor == x[j]) && ++k;
				k > m && (h = f._methods[i], m = k);
			}
		}
		return h ? h[0].apply(f, args) : undefined;
	};
	f._methods = {};
	f.overload = function(f, args){
		this._methods["#" + (args = [].slice.call(arguments, 1)).join("")] = [f, args];
	};
	f.unoverload = function(args){
		return delete this._methods["#" + [].slice.call(arguments).join("")];
	};
	return f;
};