Home > OS >  Workaround for ES6 class to have multiple constructors?
Workaround for ES6 class to have multiple constructors?

Time:08-11

I'm trying to create an ES6 class with two constructors. The code looks something like this:

class MyClass {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }

  constructor(c) {
    this.a = c;
    this.b = c;
  }
}

But I'm getting the syntax error Uncaught SyntaxError: A class may only have one constructor. Is there any workaround that would let me have multiple constructors or am I just limited constructor in JS?

CodePudding user response:

JavaScript doesn't have built-in overloading. But you can do what you want using a default argument.

class myClass {
    constructor(a, b = a) {
        this.a = a;
        this.b = b;
    }
}

If it's not as simple as your example, you can give b some other default that's not a possible actual value. Then you can check if the value is the default and run different code.

class myClass {
    constructor(a, b = undefined) {
        if (b === undefined) {
            // do the 1-argument initialization
        } else {
            // do the 2-argument initialization
        }
    }
}
  • Related