Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  81] [ 2]  / answers: 1 / hits: 20506  / 12 Years ago, tue, october 2, 2012, 12:00:00

I use method overloading as below in my Javascript code.



function somefunction()
{
//1st function
}

function somefunction(a)
{
//2nd function
}

function somefunction(a,b)
{
//3rd function
}

somefunction(); // function call goes here


What I don't understand is if I call the somefunction() javascript should call the 1st function but the problem is javascript actually calls the 3rd function. Why is that? How can I call the 1st and 2nd function ? What is the reason for this? Is there a proper way to implement method overloading in Javascript? What's the industry standard?


More From » jquery

 Answers
19

JavaScript does not support method overloading (as in Java or similiar), your third function overwrites the previous declarations.



Instead, it supports variable arguments via the arguments object. You could do



function somefunction(a, b) {
if (arguments.length == 0) { // a, b are undefined
// 1st body
} else if (arguments.length == 1) { // b is undefined
// 2nd body
} else if (arguments.length == 2) { // both have values
// 3rd body
} // else throw new SyntaxError?
}


You also could just check for typeof a == undefined etc, this would allow calling somefunction(undefined), where arguments.length is 1. This might allow easer calling with various parameters, e.g. when you have possibly-empty variables.


[#82792] Monday, October 1, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrances

Total Points: 184
Total Questions: 100
Total Answers: 92

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
;