How can implement overloading in JavaScript/jQuery?

I trying to call functions with same signature.

example: There are two functions with same name:

<script>
    var obj1,obj2,obj3,obj4,obj5;
    function OpenBox(obj1,obj2){
    // code
    }
    function OpenBox(obj1,obj2,obj3,obj4,obj5){
    // code
    }
</script>

When I calling function on click event of link

<a id='hlnk1' href='#' onclick='OpenBox(this,"abhishek"); return false;'> Open Box </a>

When I click on the above link it is calling function OpenBox(obj1,obj2,obj3,obj4,obj5) {}

It should be call function OpenBox(obj1,obj2) {} Instead.

What's going wrong in functions?


mattn has the correct idea. Because javascript has no typing those functions are equivalent. What you could do is something like this:

function OpenBox_impl1(obj1,obj2){
    // code
}
function OpenBox_impl2(obj1,obj2,obj3,obj4,obj5){
    // code
}

function OpenBox(obj1, obj2, obj3, obj4, obj5) {
    if(arguments.length == 2)
        return OpenBox_impl1(obj1, obj2);
    else
        return OpenBox_impl2(obj1,obj2,obj3,obj4,obj5);
}

javascript can't define duplicate function in same scope. check arguments.length are 2 or 5.


@abshik ,

There is nothing like that which is similar to c# or java. Javasccript behaves this way

function Test(arg1 ,arg2 , arg3, arg4)
{

}

when you are calling this function you can call in the following ways

Test(arg1);
Test(arg1,arg2);
Test(arg1,arg2,arg3);
Test(arg1,arg2,arg3,arg4);

But sequence matters , so you can the function in the above ways.

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

上一篇: 在JavaScript中的多个构造函数

下一篇: 如何在JavaScript / jQuery中实现重载?