Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"method overloading" in javascript

So I admit that I'm new to javascript and that I come from a C.+ background ("Hi, I'm Bob, I'm a class-based static language user", chorus "hi Bob!").

I find that I often end up writing functions like:

function someFunc()
{
    if (arguments.length === 0 ){
       ...
    } else {
       ...
    }
}

(where there might be three such cases). Or, alternatively, I write the difference into the name:

function someFuncDefault() { ... };
function someFuncRealArg(theArg) { ... };

(Substitute "RealArg" for some semantically contentful phrase).

Is there a better pattern for this kind of thing?

like image 307
Afton Avatar asked Mar 13 '26 13:03

Afton


2 Answers

I don't know that I would do it this way, but it seems like it might make your code mildly less unmanageable:

function someFunc() {
    switch (arguments.length) {
        case 0: noArgs();
        case 1: oneArg(arguments[0]);
        case 2: twoArgs(arguments[0], arguments[1]);
    }
    function noArgs() {
        // ...
    }
    function oneArg(a) {
        // ...
    }
    function twoArgs(a, b) {
        // ...
    }
}

Another example might be:

function someFunc(a, b) {
    if ('string' == typeof a) {
        // ...
    } else if ('number' == typeof a) {
        // ...
    }
}

And of course you can probably create something quite unmanageable by combining both examples (using conditions to determine behaviour based on number of arguments and types of arguments).

like image 126
Grant Wagner Avatar answered Mar 16 '26 02:03

Grant Wagner


This is overloading, not overriding no?

Javascript is weakly typed, so method signatures and native support is out. My recommendation is to pass an extensible object as the solitary argument. Inspect and handle the existance of properties on the param object as you wish.

What advantage does this have over arguments? Well it lets you be explicit about your intentions where you call, and unambiguous about the meaning of arg1 and arg2 where you recieve, and it lets you abstract to a custom data object class you can extend functionality to.

function someFunc(params)
{
  var x = params.x || defaultX;
  var y = params.y || defaultY;

  //businesslogic
}

someFunc({x:'foo',y:'bar'});

someFunc({y:'baz'});
like image 45
annakata Avatar answered Mar 16 '26 03:03

annakata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!