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?
javascript can't define duplicate function in same scope. check
arguments.length
are 2 or 5.The issue is that you are trying to overload a function but that is not supported by Javascript. I think your best option is to use Polymorphism instead. View this article for more details: http://www.cyberminds.co.uk/blog/articles/polymorphism-in-javascript.aspx
mattn has the correct idea. Because javascript has no typing those functions are equivalent. What you could do is something like this:
You cannot overload functions in JavaScript. Instead, the most recently defined version of the function will be used, which is why in your case the version with 5 parameters is called (the final 3 are just
undefined
).There are several ways around this, one if which is shown in Mikola's answer. An alternative is to pass in an object, and then check the contents of that object in the function (see this question):
Another option is to check
arguments.length
:in the polymorphism you can use a different signature method ,in javascript we can simulate polymorphism checking the type of the function parameter and execute certain task.
Check this example in JSFIDDLE
@abshik ,
There is nothing like that which is similar to c# or java. Javasccript behaves this way
when you are calling this function you can call in the following ways
But sequence matters , so you can the function in the above ways.