Thursday 29 December 2016

how to do overloading in javascript?

I am trying to learn overloading in javascript. I Googled it and there is a way to do that using arguments length and then by adding switch condition. But I am not interested in doing it like that. Actually I saw one good answer at
Function overloading in Javascript - Best practices but he did not give any example of overloading using his opinion. So, how do you do overloading in javascript.



Here is my code. I need to overload a method using the above solution. He said to do like that: http://jsfiddle.net/m84fg8ac/




function foo(a, b, opts) {

}


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



How I will achieve this in my code?



function foo(a, b, opts) {

}

function foo(a) {
console.log("one argument pass");
}


function foo(a, b) {
console.log("two argument pass");
}

function foo(a, b, c) {
console.log("three argument pass");
}


foo(1);

foo(1,2);
foo(1,2,3);


here it is written
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.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...