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

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

    I want to write my Javascript class like below

    You can't, in the same way you can't overload standard functions like that. What you can do is use the arguments object to query the number of arguments passed:

    class Option {
        constructor(key, value, autoLoad) {
            // new Option()
            if(!arguments.length) {
                this.autoLoad = false;
            }
            // new Option(a, [b, [c]])
            else {
                this[key] = value;
                this.autoLoad = autoLoad || false;
            }
        }
    }
    

    Babel REPL Example

    Of course (with your updated example), you could take the approach that you don't care about the number of arguments, rather whether each individual value was passed, in which case you could so something like:

    class Option {
        constructor(key, value, autoLoad) {
            if(!key) { // Could change this to a strict undefined check
                this.autoLoad = false;
                return;
            }
            this[key] = value;
            this.autoLoad = autoLoad || false;
        }
    }
    

提交回复
热议问题