Tuesday, 15 January 2019

How can implement overloading in JavaScript/jQuery?



I trying to call functions with same signature.



example: There are two functions with same name:






When I calling function on click event of link




 Open Box 


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?


Answer




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);
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...