Search code examples
javascriptdesign-patternsoop

JavaScript pattern for multiple constructors


I need different constructors for my instances. What is a common pattern for that?


Solution

  • How do you find this one?

    function Foobar(foobar) {
        this.foobar = foobar;
    }
    
    Foobar.prototype = {
        foobar: null
    };
    
    Foobar.fromComponents = function(foo, bar) {
        var foobar = foo + bar;
        return new Foobar(foobar);
    };
    
    //usage: the following two lines give the same result
    var x = Foobar.fromComponents('Abc', 'Cde');
    var y = new Foobar('AbcDef')