I need different constructors for my instances. What is a common pattern for that?
ベストアンサー1
JavaScript doesn't have function overloading, including for methods or constructors.
If you want a function to behave differently depending on the number and types of parameters you pass to it, you'll have to sniff them manually. JavaScript will happily call a function with more or fewer than the declared number of arguments.
function foo(a, b) {
if (b===undefined) // parameter was omitted in call
b= 'some default value';
if (typeof(a)==='string')
this._constructInSomeWay(a, b);
else if (a instanceof MyType)
this._constructInSomeOtherWay(a, b);
}
You can also access arguments
as an array-like to get any further arguments passed in.
If you need more complex arguments, it can be a good idea to put some or all of them inside an object lookup:
function bar(argmap) {
if ('optionalparam' in argmap)
this._constructInSomeWay(argmap.param, argmap.optionalparam);
...
}
bar({param: 1, optionalparam: 2})
Python demonstrates how default and named arguments can be used to cover the most use cases in a more practical and graceful way than function overloading. JavaScript, not so much.