-1

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.

Community
  • 1
  • 1
user944513
  • 12,247
  • 49
  • 168
  • 318
  • JS doesn't support overloading, so I'm not sure how you expect your second snippet to work. Each time you redeclare `foo` previous declarations are lost. – Asad Saeeduddin May 03 '15 at 00:16
  • 3
    Can you explain a bit more about why you don't want to check the `arguments` length? Asking how to do something, but arbitrarily restricting one of the ways to do it, seems a bit odd. To put it a different way, what makes your question different from the one you've linked to? – IMSoP May 03 '15 at 00:17
  • I am able to do using or checking arument length but I want to do like that http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices – user944513 May 03 '15 at 00:20
  • @IMSoP yes I am trying to do same but how I will do that – user944513 May 03 '15 at 00:20
  • @IMSoP could you please give your answer in fiddle using stackoverflow anser – user944513 May 03 '15 at 00:22
  • 1
    @user944513 I am not proposing any answer. I am proposing to close this question as a duplicate, because it doesn't ask anything not asked in the previous question. Not feeling that the answers on that question give enough information is not sufficient reason to open a new question. – IMSoP May 03 '15 at 00:24
  • 1
    This is definitely a duplicate since user944513 keeps citing the previously posted question, asking for "that solution". – Patrick Roberts May 03 '15 at 00:27
  • http://ejohn.org/blog/javascript-method-overloading/ – Miguel Mota May 03 '15 at 00:30
  • I think part of the disconnect here is that your example is explicitly varying based on the *number* of arguments, which would best be achieved by checking `arguments.length` or using optional parameters, whereas the answer you are asking for clarification on suggests *a different way of organising your functions*, so that you can pass lots of different optional parameters. It makes no sense to demonstrate one in terms of the other. – IMSoP May 03 '15 at 00:39
  • I will check from argument length.Thank for support – user944513 May 03 '15 at 00:43
  • 1
    @user944513 If your method is doing entirely different things depending on the number of arguments, maybe it would be better to make 3 different functions? If your method does pretty much the same for each, why not make it argument length abstract? If you just want to set defaults, just have one method and set defaults! – Paul S. May 03 '15 at 01:20

3 Answers3

1

JavaScript doesn't require all the arguments to be passed when calling a function, so overloading can be achieved like so:

function foo(a, b, c) {
    if (c === undefined) {
        if (b === undefined) {
            if (a === undefined) console.log("zero argument pass");
            else console.log("one argument pass");
        }
        else console.log('two argument pass');
    }
    else console.log('three argument pass');
}
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
  • what is that solution http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices – user944513 May 03 '15 at 00:17
1

From http://ejohn.org/blog/javascript-method-overloading/

var namespace = {};

function addMethod(object, name, fn) {
    var old = object[name];
    object[name] = function() {
        if (fn.length === arguments.length) {
            return fn.apply(this, arguments);
        } else if (typeof old === 'function') {
            return old.apply(this, arguments);
        }
    };
}

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

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

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

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

var namespace = {};

function addMethod(object, name, fn) {
    var old = object[name];
    object[name] = function() {
        if (fn.length === arguments.length) {
            return fn.apply(this, arguments);
        } else if (typeof old === 'function') {
            return old.apply(this, arguments);
        }
    };
}

addMethod(namespace, "foo", function (a) {
    document.write("one argument pass<br/>");
});

addMethod(namespace, "foo", function (a, b) {
    document.write("two arguments pass<br/>");
});

addMethod(namespace, "foo", function (a, b, c) {
    document.write("three argument pass<br/>");
});

namespace.foo(1);
namespace.foo(1, 2);
namespace.foo(1, 2, 3);
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
0

Check the arity

function foo(a, b, opts) {
    if (arguments.length === 1) {
        console.log("one argument pass")
    } else if (arguments.length === 2) {
        console.log("two argument pass")
    } else if (arguments.length === 3) {
        console.log("three argument pass")
    }
}

foo(1); // "one argument pass"
foo(1,2); // "two argument pass"
foo(1,2,3); // "three argument pass"

http://jsfiddle.net/m84fg8ac/2/

Community
  • 1
  • 1
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • i need to use this solution http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices – user944513 May 03 '15 at 00:18
  • Why do you clone the `arguments` object? Also check https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments – zerkms May 03 '15 at 00:18
  • 1
    @user944513 You keep linking to a question and saying you need to use that "solution". What solution are you talking about? – Asad Saeeduddin May 03 '15 at 00:23
  • http://stackoverflow.com/questions/456177/function-overloading-in-javascript-best-practices – user944513 May 03 '15 at 00:24
  • please check above link – user944513 May 03 '15 at 00:24
  • 1
    @user944513 That is a link to a question with more than 20 different answers, not a single "solution". – IMSoP May 03 '15 at 00:26
  • accepted one answer having 286 upvotes..function foo(a, b, opts) { } – user944513 May 03 '15 at 00:27
  • or in other words 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. – user944513 May 03 '15 at 00:29
  • 1
    @user944513 That is a way to avoid having to do any function overloading whatsoever. You replace any optional arguments with a single argument that is supposed to be passed a `{}`. You look for all your optional arguments inside that `{}`. – Asad Saeeduddin May 03 '15 at 00:31
  • @Asad please provide fiddle so better understant..mean how i apply this in my example – user944513 May 03 '15 at 00:35
  • @user944513 That answer does only show how the calling side works but within the function it is similar to the answer's that use Arguments. It will still have to check for nulls. There is no true function overloading there are just functions that look really hard at the information they were given to decide what to do. – drs9222 May 03 '15 at 00:51
  • @user944513 If you insist on simulating overloading by being able to call a single function with different arguments than you will have to incur the cost associated with checking to see which "version of the function" is intended. If you don't want that cost then you have to give the functions unique names. – drs9222 May 03 '15 at 00:51
  • So best way to do that using check argument length ? – user944513 May 03 '15 at 00:55