method and function overloads in javascript and jquery

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


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.]


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 ie by passing an object.. (check link for reference)

链接地址: http://www.djcxy.com/p/51994.html

上一篇: 如何在Asp.Net MVC 2中通过JQuery调用重载的C#函数

下一篇: 方法和函数重载在JavaScript和jQuery中