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

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

I want to write my Javascript class like below.

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

    constructor(key, value) {
               


        
8条回答
  •  旧时难觅i
    2020-12-03 05:00

    What you want is called constructor overloading. This, and the more general case of function overloading, is not supported in ECMAScript.

    ECMAScript does not handle missing arguments in the same way as more strict languages. The value of missing arguments is left as undefined instead of raising a error. In this paradigm, it is difficult/impossible to detect which overloaded function you are aiming for.

    The idiomatic solution is to have one function and have it handle all the combinations of arguments that you need. For the original example, you can just test for the presence of key and value like this:

    class Option {
      constructor(key, value, autoLoad = false) {
        if (typeof key !== 'undefined') {
          this[key] = value;
        }
        this.autoLoad = autoLoad;
      }
    }
    

提交回复
热议问题