nagoon97’s Weblog

you can actually do alot with javascript!

Method overloading in Javascript March 11, 2008

Filed under: ajax,javascript — nagoon97 @ 4:51 pm
Tags: , , ,

To simulate method overloading in Javascript, many “if” statements are often used, which makes the code alot less intuitive.

So, I came up with the following function to simulate method overloading without harming the readability of the source code.

/**
 * You can find more about this function at
 * http://nagoon97.com/method-overloading-in-javascript/
 *
 * Copyright (c) 2008 Andy G.P. Na
 * The source code is freely distributable under the terms of an MIT-style license.
 */
function methodOverloading(funcName, args){
var sFuncName = funcName;
var func = null;

sFuncName += “$”+getType(args[0]);
for(var i=1; iHERE.
getType() is used to give methodOverloading() function the ability to overload method with user defined custom objects.
If this feature is not needed and you do not want to include the function, you can change it to typeof() and use it as

function methodOverloading(funcName, args){
var sFuncName = funcName;
var func = null;

sFuncName += “$”+typeof(args[0]);
for(var i=1; i

 

3 Responses to “Method overloading in Javascript”

  1. Good stuff, but last I checked, typeof is an operator and not a function, so in the alternate version, it’ll be

    typeof args[0]

    instead of

    typeof(args[0])

  2. nagoon97 Says:

    Hello Jaffer ^-^
    Yes, you are right, typeof is an operator but placing parentheses around the operand is allowed and I think it makes the source code easier to read because the operator looks alot like a name of an instance without the parentheses.

    alert(type1 + typeof(type2) + type3);
    alert(type1 + typeof type2 + type3);

  3. cool, didn’t know that.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 32 other followers