dev

February 21, 2008

Introducing overload.js

Filed under: Javascript, MooTools, OOP — Tags: , , , — Zeal_ @ 10:09 pm

Overload.js is a tiny but handy library for MooTools, my attempt at shaping Javascript towards being a more OOP-esque language. It lets you overload methods of a class to do different things based on their actual parameters.

Although it is not production code yet, it works pretty much as expected. Call it 0.1, and maybe spice it with a touch of “beta” too ;)

A class with an overloaded method, setColor, looks like this:

var Color=new Class({
	r:0,
	g:0,
	b:0,
	initialize:function() {
	},
	setColor:overload({
		"string":function(s) {
			var r = parseInt(s.substr(1,2), 16);
			var g = parseInt(s.substr(3,2), 16);
			var b = parseInt(s.substr(5,2), 16);
			this.setColor(r,g,b);
		},
		"int int int":function(r,g,b) {
			this.r = r;
			this.g = g;
			this.b = b;
		}
	}),
	toString:function() {
		return '#' + this.r.toString(16) + this.g.toString(16) + this.b.toString(16);
	}
});

Here, setColor may be called with either one argument of the type ‘string’, or three arguments of the type ‘int’. It is worth noting that type matching is done via the following function:

function match_type(type_name, arg) {
    switch(type_name) {
        case 'string': return $type(arg) == 'string';
        case 'int': return ($type(arg) == 'number') && (!arg.toString().contains('.'));
        case 'float': return ($type(arg) == 'number') && (arg.toString().contains('.'));
        case 'array': return ($type(arg) == 'array');
        case 'object': return ($type(arg) == 'object');
    }
    return eval('arg instanceof ' + type_name);
}

Thus,

  • a string, an array or an object argument is recognized based on their types
  • a float or an integer argument is recognized based on their type being number, and whether if they contain or don’t contain a decimal dot, respectively.
  • an argument of any class (e.g. Element or Ajax) is recognized using eval and instanceof.

I think the most serious problem with the current implementation is that there is no fallback mechanism should formal parameter type matching fail. So,


var c = new Color();

c.setColor("first", "second");

doesn’t call any of the overloaded methods, nor does it notify the user.

Please find attached overload.js in its present form: overload.js.

Comments are welcome! :)

Create a free website or blog at WordPress.com.