JavaScript pattern for multiple constructors

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

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

9条回答
  •  轮回少年
    2020-12-07 13:30

    Answering because this question is returned first in google but the answers are now outdated.

    You can use Destructuring objects as constructor parameters in ES6

    Here's the pattern:

    You can't have multiple constructors, but you can use destructuring and default values to do what you want.

    export class myClass {
    
      constructor({ myArray = [1, 2, 3], myString = 'Hello World' }) {
    
        // ..
      }
    }
    

    And you can do this if you want to support a 'parameterless' constructor.

    export class myClass {
    
          constructor({myArray = [1, 2, 3], myString = 'Hello World'} = {}) {
    
            // ..
          }
    }
    

提交回复
热议问题