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

前端 未结 8 2135
终归单人心
终归单人心 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 05:05

    Guessing from your sample code, all you need is to use default values for your parameters:

    class Option {
        constructor(key = 'foo', value = 'bar', autoLoad = false) {
            this[key] = value;
            this.autoLoad = autoLoad;
        }
    }
    

    Having said that, another alternative to constructor overloading is to use static factories. Suppose you would like to be able to instantiate an object from plain parameters, from a hash containing those same parameters or even from a JSON string:

    class Thing {
        constructor(a, b) {
            this.a = a;
            this.b = b;
        }
    
        static fromHash(hash) {
            return new this(hash.a, hash.b);
        }
    
        static fromJson(string) {
            return this.fromHash(JSON.parse(string));
        }
    }
    
    let thing = new Thing(1, 2);
    // ...
    thing = Thing.fromHash({a: 1, b: 2});
    // ...
    thing = Thing.fromJson('{"a": 1, "b": 2}');
    
    0 讨论(0)
  • 2020-12-03 05:05

    Use object.assigne with arguments with this

    This={...this,...arguments}
    
    0 讨论(0)
提交回复
热议问题