0

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 this 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 to one constructor in JS?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Sounds like a duplicate of [method overloading in JavaScript](https://stackoverflow.com/questions/12694588/method-overloading-in-javascript)? – Bergi Oct 24 '22 at 02:39
  • @Bergi The answers are quite similar, but the questions themselves are fairly different. The error message makes me think that two constructors might be a bit different than redefining a function. – Michael M. Oct 24 '22 at 12:54

1 Answers1

4

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
        }
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612