8

is it possible to have more than one constructors for a class in javascript? i.e. one with zero parameters, one with one, one with two, etc...

if so, how?

thanks!

2

2 Answers 2

9

No, Javascript does not support function overloading.

However, inside every function you have access to an arguments object, which holds all the arguments supplied to the function, declared or not. You can simply look at it and decide what exactly you want to do in your constructor.

Bad, unrefined example:

function Foo() {

    function singleParamConstructor(foo) {
        ...
    }
    function twoParamConstructor(foo, bar) {
        ...
    }

    switch (arguments.length) {
        case 1 :
            singleParamConstructor(arguments[0]);
            break;
        case 2 :
            twoParamConstructor(arguments[0], arguments[1]);
            break;
        ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any other way apart from this one?
Well, no, Javascript does not support function overloading. There are probably innumerable design patterns with which you can avoid getting into a situation in which you think you need function overloading to begin with though.
1

this might help: JavaScript constructor parameter types

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.