Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: different constructors for same type of object

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!

like image 535
clamp Avatar asked Feb 07 '11 09:02

clamp


2 Answers

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;
        ...
    }
}
like image 161
deceze Avatar answered Oct 26 '22 08:10

deceze


this might help: JavaScript constructor parameter types

like image 23
Davide Piras Avatar answered Oct 26 '22 09:10

Davide Piras