Thursday, August 21, 2014

Method overloading in javascript

When we  use method overloading as below in javascipt code.

 function anyfunction()  
 {  
   //1st function  
 }  
 function anyfunction(a)  
 {  
   //2nd function  
 }  
 function anyfunction(a,b)  
 {  
   //3rd function  
 }  
 anyfunction(); // function call goes here  

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. We can handle like this,

 function anyfunction(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?  
 }  

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

 function anyFunction(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  
   }  
 }  


No comments:

Post a Comment

Popular Posts