Alas, JavaScript can't handle multiple constructors! You get one and only one.
There are some things you can do to pretend to have more than one - you can check the incoming data, and assign sane defaults:
@JsConstructor
public Dog(@JsOptional String name) {
if (name == null) {
name = "Scooby Doo";
}
this.name = name;
}
You have to be careful of types here if your two constructors do not use the same types in the same position - judicious use of instanceof
might work (just be aware that for JS objects you are using JS instanceof
, not java!). Another option lets you be more flexible, but again, no overloaded methods - factory methods:
public static Dog withName(String name) {
return new Dog(name);
}
public static Doc defaultImpl() {
return new Dog();
}
@JsIgnore
public Dog() {/*...*/}
@JsIgnore
public Dog(String name) {/*...*/}
Another idea on the same theme would be to create a JsType builder. This is a bit less idiomatic for JS.
Finally, you could consider the dreaded "options object", where your one constructor takes a single Object with properties, or a JsPropertyMap<Any>
holding all the possible values, then check nullness and types inside the giant constructor. I avoid this personally - this is one of the terrible things I'm hoping to avoid by writing Java in the first place.