0

This question is the same: [How do I call one constructor from another in Java?, but JavaScript.

I read that JavaScript does not support multiple declarations of constructors in a class, Is it true?

So, Can I implement the following piece of code?

class A {
  constructor(a,b){
    console.log([a,b]);
  }

  constructor(obj) {
    console.log(obj.a,obj.b);
  }
}

let x1 = new A(2,4);
let x2 = new A({a:2,b:4});

Coming back the original question:

class A {
  constructor(a,b){
    console.log(a+b);
  }

  constructor(obj) {
    this(obj.a,obj.b);
  }
}

let x1 = new A(2,4);
let x2 = new A({a:2,b:4});

If not, What would the most "transparent" design pattern be to do it?

Naive Developer
  • 700
  • 1
  • 9
  • 17

1 Answers1

5

JavaScript doesn’t support overloading of any kind, because function signatures and function calls don’t have to match. On the other hand, function signatures and function calls don’t have to match:

class A {
  constructor(a, b) {
    if (b === undefined) {
      ({a, b} = a);
    }

    console.log(a + b);
  }
}

new A(1, 2);
new A({a: 3, b: 4});

This can get confusing fast, though, so consider if it’s better design not to do it, either by eliminating one overload that isn’t really necessary or splitting it out into another function:

class A {
  constructor({a, b}) {
    console.log(a + b);
  }

  static of(a, b) {
    return new this({a, b});
  }
}

A.of(1, 2);
new A({a: 3, b: 4});
Ry-
  • 218,210
  • 55
  • 464
  • 476