In a traditional OO language, multiple constructors are nothing special. You simply add overloaded versions of the constructor function, much as you add overloaded versions to any method. But JavaScript doesn't enforce strict argument lists and doesn't have a concept of function overloading.
Definition and Usage Note: A class cannot have more than one constructor() method.
In TypeScript, we cannot define multiple constructors like other programming languages because it does not support multiple constructors.
Having more than one occurrence of a constructor method in a class will throw a SyntaxError error.
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.
you can use class with static methods that return an instance of that class
class MyClass {
constructor(a,b,c,d){
this.a = a
this.b = b
this.c = c
this.d = d
}
static BAndCInstance(b,c){
return new MyClass(null,b,c)
}
static BAndDInstance(b,d){
return new MyClass(null,b, null,d)
}
}
//new Instance just with a and other is nul this can
//use for other params that are first in constructor
const myclass=new MyClass(a)
//an Instance that has b and c params
const instanceWithBAndC = MyClass.BAndCInstance(b,c)
//another example for b and d
const instanceWithBAndD = MyClass.BAndDInstance(b,d)
with this pattern you can create multi constructor
How do you find this one?
function Foobar(foobar) {
this.foobar = foobar;
}
Foobar.prototype = {
foobar: null
};
Foobar.fromComponents = function(foo, bar) {
var foobar = foo + bar;
return new Foobar(foobar);
};
//usage: the following two lines give the same result
var x = Foobar.fromComponents('Abc', 'Cde');
var y = new Foobar('AbcDef')
Didn't feel like doing it by hand as in bobince's answer, so I just completely ripped off jQuery's plugin options pattern.
Here's the constructor:
//default constructor for Preset 'class'
function Preset(params) {
var properties = $.extend({
//these are the defaults
id: null,
name: null,
inItems: [],
outItems: [],
}, params);
console.log('Preset instantiated');
this.id = properties.id;
this.name = properties.name;
this.inItems = properties.inItems;
this.outItems = properties.outItems;
}
Here's different ways of instantiation:
presetNoParams = new Preset();
presetEmptyParams = new Preset({});
presetSomeParams = new Preset({id: 666, inItems:['item_1', 'item_2']});
presetAllParams = new Preset({id: 666, name: 'SOpreset', inItems: ['item_1', 'item_2'], outItems: ['item_3', 'item_4']});
And here's what that made:
presetNoParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}
presetEmptyParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}
presetSomeParams
Preset {id: 666, name: null, inItems: Array[2], outItems: Array[0]}
presetAllParams
Preset {id: 666, name: "SOpreset", inItems: Array[2], outItems: Array[2]}
Going further with eruciform's answer, you can chain your new
call into your init
method.
function Foo () {
this.bar = 'baz';
}
Foo.prototype.init_1 = function (bar) {
this.bar = bar;
return this;
};
Foo.prototype.init_2 = function (baz) {
this.bar = 'something to do with '+baz;
return this;
};
var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');
Answering because this question is returned first in google but the answers are now outdated.
You can use Destructuring objects as constructor parameters in ES6
Here's the pattern:
You can't have multiple constructors, but you can use destructuring and default values to do what you want.
export class myClass {
constructor({ myArray = [1, 2, 3], myString = 'Hello World' }) {
// ..
}
}
And you can do this if you want to support a 'parameterless' constructor.
export class myClass {
constructor({myArray = [1, 2, 3], myString = 'Hello World'} = {}) {
// ..
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With