JavaScript pattern for multiple constructors

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

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

9条回答
  •  -上瘾入骨i
    2020-12-07 13:28

    Going further with eruciform's answer, you can chain your new call into your init method.

    function Foo () {
        this.bar = 'baz';
    }
    
    Foo.prototype.init_1 = function (bar) {
        this.bar = bar;
        return this;
    };
    
    Foo.prototype.init_2 = function (baz) {
        this.bar = 'something to do with '+baz;
        return this;
    };
    
    var a = new Foo().init_1('constructor 1');
    var b = new Foo().init_2('constructor 2');
    

提交回复
热议问题