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?
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.
JS will pass undefined
to any parameters which are not provided. If you want something like overloading, you'll need to do something similar to the code below:
function someFunction(a, b) { if (typeof a === 'undefined') { // Do the 0-parameter logic } else if (typeof b === 'undefined') { // Do the 1-parameter logic } else { // Do the 2-parameter logic } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With