How to overload constructor of an Object in JS (Javascript)?

I like Ilya Volodins answer and I thought I would add this as an example:

function foo() {
    var evt = window.event || arguments[1] || arguments.callee.caller.arguments[0];
    var target = evt.target || evt.srcElement;

    var options = {};

    if (arguments[0]) options = arguments[0];

    var default_args = {
        'myNumber'      :   42,
        'myString'      :   'Hello',
        'myBoolean'     :   true
    }
    for (var index in default_args) {
        if (typeof options[index] == "undefined") options[index] = default_args[index];
    }

    //Do your thing

}

//then you call it like this
foo();

//or

foo({'myString' : 'World'});

//or

foo({'myNumber' : 666, 'myString' : 'World', 'myBoolean' : false});

There are probably nicer ways of doing this but this just one example.


You can't do that, since JavaScript is not a strongly typed language it will not see a difference between form and userName. You can create multiple function like createUserFromForm(form) and createUserFromUserInfo(userName, password,...) or you could try to use a singular constructor with no arguments specified and then use arguments collection to check the input and decide what to do.


No you can't, JavaScript does not support overloading of any kind.

What you can do is either pass an object which has already been populated with the values into your constructor and then grab the values from the object, but this which duplicates code.

Or you can create a default constructor and add methods such as initFromUser or setFromForm which then take the respective parameters and setup the objects values, new User().initFormForm(form) looks pretty clean to me.