Method overloading in JavaScript

JavaScript/Ajax Add comments

If you have been programming for any length of time you probably know what method overloading is or have at least heard of it.

What is method overloading?

Method overloading is a feature found in various object oriented programming languages such as C#, C++ and Java that allows the creation of several functions with the same name which differ from each other in terms of the type of the input and the type of the output of the function.

[Wikipedia]

With the formalities out of the way, there are times when method overloading can be very helpful. JavaScript is no exception. The problem is it is not as apparent how to achieve method overloading in JavaScript because it doesn’t work the same as more traditional languages do.

What won’t work

Let’s look at implementing an overloaded function how you would think it should work.

function myFunction() {
  //function with no arguments
}

function myFunction(arg) {
	//overloaded function with one argument
}

Now JavaScript will accept this and you may think you are done. Think again. You do not have an overloaded function. In the above example your second function definition just overwrote the first so you only have a function that excepts one argument. I told you it doesn’t work the same.

What will work

Now that we have looked at what won’t work let’s take a look at the proper way to implement an overloaded function.

Let’s look at a simple example using bunnies. Awww, how cute.

function getBunnyColor() {
	var name = arguments[0] == null ? 'peter' : arguments[0];
	switch(name) {
		case 'peter':
			return 'brown';
			break;
		case 'flopsy':
			return 'white';
			break;
		default:
			return 'unknown bunny';
			break;
	}
}

getBunnyColor(); //-> 'brown'
getBunnyColor('flopsy'); //-> 'white'

What is that?

Now I’ll explain what I did. Every function has an array called arguments. This array contains the arguments that are passed into the function even if specific arguments are declared in the function definition.

So knowing that I didn’t bother to declare any arguments when I defined the function. I instead used the arguments array to detect what had been passed in. If arugments[0] was null (no argument had been passed) then I assigned a default name of ‘peter’.

Conclusion

So JavaScript implements method overloading a bit differently than most languages meaning your function definitions will look different but you use the overloaded functions the same way. Hope this helps you out!

Popularity: 17% [?]

If you liked this article consider subscribing to my free rss article feed to automatically get new articles in your feed reader.

Leave a Reply

WP Theme & Icons by N.Design Studio
Entries RSS Login