Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading in Javascript

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?

like image 727
Techie Avatar asked Oct 02 '12 16:10

Techie


2 Answers

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.

like image 128
Bergi Avatar answered Sep 20 '22 23:09

Bergi


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     } } 
like image 39
carlosfigueira Avatar answered Sep 18 '22 23:09

carlosfigueira