JavaScript pattern for multiple constructors

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

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

9条回答
  •  醉话见心
    2020-12-07 13:34

    you can use class with static methods that return an instance of that class

        class MyClass {
            constructor(a,b,c,d){
                this.a = a
                this.b = b
                this.c = c
                this.d = d
            }
            static BAndCInstance(b,c){
                return new MyClass(null,b,c)
            }
            static BAndDInstance(b,d){
                return new MyClass(null,b, null,d)
            }
        }
    
        //new Instance just with a and other is nul this can
        //use for other params that are first in constructor
        const myclass=new MyClass(a)
    
        //an Instance that has b and c params
        const instanceWithBAndC = MyClass.BAndCInstance(b,c)
    
        //another example for b and d
        const instanceWithBAndD = MyClass.BAndDInstance(b,d)
    

    with this pattern you can create multi constructor

提交回复
热议问题