Why doesn't JavaScript ES6 support multi-constructor classes?

前端 未结 8 2200
终归单人心
终归单人心 2020-12-03 04:25

I want to write my Javascript class like below.

class Option {
    constructor() {
        this.autoLoad = false;
    }

    constructor(key, value) {
               


        
8条回答
  •  情书的邮戳
    2020-12-03 04:45

    Another option would be to allow your constructor to take an object that is bound to your class properties:

    class Option {
      // Assign default values in the constructor object 
      constructor({key = 'foo', value, autoLoad = true} = {}) {
          this.key = key;
          // Or on the property with default (not recommended)
          this.value = value || 'bar';
          this.autoLoad = autoLoad;
          
          console.log('Result:', this);
      }
    }
    
    var option1 = new Option();
    // Logs: {key: "foo", value: "bar", autoLoad: true}
    
    var option2 = new Option({value: 'hello'});
    // Logs: {key: "foo", value: "hello", autoLoad: true}

    This is even more useful with Typescript as you can ensure type safety with the values passed in (i.e. key could only be a string, autoLoad a boolean etc).

提交回复
热议问题