How can implement overloading in JavaScript/jQuery

2019-02-13 13:07发布

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?

7条回答
闹够了就滚
2楼-- · 2019-02-13 13:59

Once a function is defined in ecmascript, that name is locked. However, you can pass any number of parameters to that function so you do the rest of the work on the inside.

function foo(arg1, arg2) {
    // any code that is needed regardless of param count

    if(arg2 !== undefined) {
        // run function with both arguments
        console.log(arguments);
    } else if(arg1 !== undefined) {
        // run function with one argument
    } else {
        // run function with no arguments
    }
}

foo(1);
foo(1,2);
foo(1,2,3);

Interesting note: you can pass in extra parameters that aren't in the function declaration. Do a console.log of arguments and you'll see everything in there. arguments is an object which can be accessed like / typecasted to an array.

查看更多
登录 后发表回答