Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't JavaScript ES6 support multi-constructor classes?

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} 
like image 883
Manhhailua Avatar asked Sep 17 '15 09:09

Manhhailua


People also ask

Can JavaScript classes have multiple constructors?

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.

Is constructor allowed in ES6 class definition?

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.

How many constructors can a class have in JavaScript?

Definition and Usage Note: A class cannot have more than one constructor() method.

Can you overload constructor in JavaScript?

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.


1 Answers

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;     } } 
like image 175
CodingIntrigue Avatar answered Sep 25 '22 11:09

CodingIntrigue