Monday, 22 August 2016

Function Overloding, Polymorphism, Method Overloding in Javascript

I often do this...

C#

In CSharp

   public string CatStrings(string p1)                  {return p1;}
   public string CatStrings(string p1, int p2)          {return p1+p2.ToString();}
   public string CatStrings(string p1, int p2, bool p3) {return p1+p2.ToString()+p3.ToString();}

   CatStrings("one");        // result = one
   CatStrings("one",2);      // result = one2
   CatStrings("one",2,true); // result = one2true
                

JS

In JavaScript

 function CatStrings(p1, p2, p3)
 {
   var s = p1;
   if(typeof p2 !== "undefined") {s += p2;}
   if(typeof p3 !== "undefined") {s += p3;}
   return s;
 };

 CatStrings("one");        // result = one
 CatStrings("one",2);      // result = one2
 CatStrings("one",2,true); // result = one2true
                

What most developers do is...

JS

JavaScript

The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.

What most developers do is tack on an object as the last argument to their methods. This object can hold anything.

 function foo(a, b, opts) {

 }

 foo(1, 2, {"method":"add"});
 foo(3, 4, {"test":"equals", "bar":"tree"});
                

Then you can handle it anyway you want in your method. [Switch, if-else, etc.]

No comments:

Post a Comment