Polymorphism in JavaScript

There are two approaches by which we can use Polymorphism in JavaScript. One by checking the argument types or by another approach by tracking an object at the last argument of a function.

Polymorphism by Checking Argument Type
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
Polymorphism by Tracking an object
function foo(a, b, opts) {
 }

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

results matching ""

    No results matching ""