3

Can I use method and function overload in java-script and JQuery, if possible it means how to do that.

I have developed following code, but I think that is wrong, what's my error I don't know that, please clarify that

    function isnull(txtid, errid, err) {  
        if (trimString(get(txtid).value) == '') {
            return false;
        }
        return true;
    }

    function isnull(txtid) {
        if (trimString(get(txtid).value) == '') {        
            return false;
        }
        return true;
    }

All the time function calls second one only, if any idea do this one

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82

2 Answers2

6

There is no real function overloading in JavaScript because javascript has no type checking on arguments or required qty of arguments, you can just have one implementation of isnull that can adapt to what arguments were passed to it by checking the type, presence or quantity of arguments.

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

function foo(a, b, opts) {

}


foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});

Then you can handle it anyway you want in your method. [Switch, if-else, etc.]

Shreyos Adikari
  • 12,348
  • 19
  • 73
  • 82
  • please can u elaborate "passed to it by checking the type, presence or quantity of arguments" –  May 22 '13 at 07:43
  • Yes Raje the elaboration is present in the link given to my answer. – Shreyos Adikari May 22 '13 at 07:44
  • 2
    he means: f(a:Int){bla;} and f(b:String){blu;} for JS it's absolutely the same so he will enter in the first f function he can find --> obviously he always execute "bla". You need to check type inside a unique f function : f(arg:Object){if(typeof(arg)==='String') blu; else if(typeof(arg)==='Integer') bla; else alert('not implemented');} [the code here is not accurate]. you really should consider using blackbee's answer with a generic options – TecHunter May 22 '13 at 07:47
2

A trick to do overloading would be like this:

function over_load(object, name, args) {
  var prev = object[name];
  object[name] = function(){
  if (args.length == arguments.length)
    return fn.apply(this, arguments);
  else if (typeof prev == 'function')
    return prev.apply(this, arguments);
  else throw "Wrong number of args"; 
  };
}

but according to the answer Function overloading in Javascript - Best practices , checking the argument length makes it slow, so there is a better way to achieve overloading i.e by passing an object.. (check link for reference)

Community
  • 1
  • 1
argentum47
  • 2,385
  • 1
  • 18
  • 20