Multiple Class Constructors in JavaScript
Last Updated :
10 Jan, 2024
Classes were introduced in ES6 and along with it the concepts of Object Oriented Programming were implemented. Even with all these new features, JavaScript does not allow constructor overloading. So, we cannot create multiple constructors for a single class in JavaScript but there are some methods with which we can make constructors behave differently according to different arguments passed.
There are three methods to make the effect of multiple classes in JavaScript:
Approach 1: Static Methods
In this approach, we will create some static methods inside the class and it will handle how the different values passed in the class will be assigned.
Example: In this example, we will use the above approach.
Javascript
class Person {
constructor(name, section, rollno, city){
this .name = name;
this .section = section;
this .rollno = rollno;
this .city = city
}
static nameandrollno(name, rollno) {
return new Person(name, "" ,rollno, "" )
}
static sectionandcity(section, city) {
return new Person( "" , section, "" , city)
}
}
let per1 = Person.nameandrollno( "Ram" , 1);
let per2 = Person.sectionandcity( "A" , "Delhi" );
console.log(per1);
console.log(per2);
|
Output
Person { name: 'Ram', section: '', rollno: 1, city: '' }
Person { name: '', section: 'A', rollno: '', city: 'Delhi' }
Approach 2: Single Object Literal Method
In this approach, we will pass the parameter as an object and it will be stored inside the class.
Example: In this example, we will use the above approach.
Javascript
class Person {
constructor(age, details){
this .age = age;
this .details = details
}
}
let per1 = new Person(12,{name: "Ram" , rollno :1,
Section: "A" , City: "Delhi" });
let per2 = new Person(12, {})
console.log(per1);
console.log(per2);
|
Output
Person {
age: 12,
details: { name: 'Ram', rollno: 1, Section: 'A', City: 'Delhi' }
}
Person { age: 12, details: {} }
Approach 3: Passing default value in optional parameters
In this approach, we will skip the value of optional parameters and they will be initialized with an undefined value. If we want a particular value to be the default value of the parameter we can assign that value to the variable in the parameter list.
Example: In this example, we will use the above approach.
Javascript
class Person {
constructor(firstName , rollno, section, city){
this .firstname = firstName,
this .rollno = rollno,
this .section = section,
this .city = city
}
}
let per1 = new Person( "Ram" , 1, "A" , "Delhi" );
let per2 = new Person( "Raj" , 2)
console.log(per1);
console.log(per2);
|
Output
Person { firstname: 'Ram', rollno: 1, section: 'A', city: 'Delhi' }
Person {
firstname: 'Raj',
rollno: 2,
section: undefined,
city: undefined
}
Share your thoughts in the comments
Please Login to comment...