I want to write my Javascript class like below.
class Option { constructor() { this.autoLoad = false; } constructor(key, value) { this[key] = value; } constructor(key, value, autoLoad) { this[key] = value; this.autoLoad = autoLoad || false; } }
I think it would be nice if we can write out class in this way. Expect to happen:
var option1 = new Option(); // option1 = {autoLoad: false} var option2 = new Option('foo', 'bar',); // option2 = {foo: 'bar'} var option3 = new Option('foo', 'bar', false); // option3 = {foo: 'bar', autoLoad: false}
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.
But in ES6, we can create the class by using the class keyword. We can include classes in our code either by class expression or by using a class declaration. A class definition can only include constructors and functions.
Definition and Usage Note: A class cannot have more than one constructor() method.
No you can't, JavaScript does not support overloading of any kind. What you can do is either pass an object which has already been populated with the values into your constructor and then grab the values from the object, but this which duplicates code.
I want to write my Javascript class like below
You can't, in the same way you can't overload standard functions like that. What you can do is use the arguments object to query the number of arguments passed:
class Option { constructor(key, value, autoLoad) { // new Option() if(!arguments.length) { this.autoLoad = false; } // new Option(a, [b, [c]]) else { this[key] = value; this.autoLoad = autoLoad || false; } } }
Babel REPL Example
Of course (with your updated example), you could take the approach that you don't care about the number of arguments, rather whether each individual value was passed, in which case you could so something like:
class Option { constructor(key, value, autoLoad) { if(!key) { // Could change this to a strict undefined check this.autoLoad = false; return; } this[key] = value; this.autoLoad = autoLoad || false; } }
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