JavaScript pattern for multiple constructors

前端 未结 9 969
不知归路
不知归路 2020-12-07 13:12

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

9条回答
  •  庸人自扰
    2020-12-07 13:21

    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')
    

提交回复
热议问题