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?

1 Answer 1

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});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.