JavaScript Class Constructor
JavaScript Class Constructor is a method inside the class used to create and initialise the object instance of this class type with supplied values.
Syntax
The syntax of an empty constructor is
constructor() {
//code
}
The syntax of an empty constructor with one argument a
is
constructor(a) {
//code
}
The syntax of an empty constructor with three arguments: a
, b
, and c
is
constructor(a, b, c) {
//code
}
Properties
- Only one constructor is allowed in a class. We cannot define more than one constructor in a class.
- If constructor is not defined for a class, then a default constructor is supplied for the class.
Examples
In the following example, we define a class Student with a constructor that can accept two arguments.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
}
var s1 = new Student('Arjun', 13);
var result = s1.getDetails('Essay on Elephant');
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
When creating a new Student object using new Student('Arjun', 13)
, the values are passed for the constructor.
If the arguments supplied to the constructor are less than that of the defined arguments, then the initial arguments which got values are initialized and the rest remain undefined
.
In the following example, we create Student
type object instance with only name
passed for the constructor. We have not pass the roll_no
. Therefore, only name
is initialized and the roll_no
remain undefined.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
}
var s1 = new Student('Arjun');
var result = s1.getDetails('Essay on Elephant');
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
If we pass more arguments for constructor than that of actually defined, the excess are discarded.
In the following example, we passed three values for the Student class constructor. Since, Student constructor is defined with only two arguments, the third value pass for the constructor shall be ignored.
index.html
<!DOCTYPE html>
<html lang="en">
<body>
<pre id="output"></pre>
<script>
class Student {
constructor(name, roll_no) {
this.name = name;
this.roll_no = roll_no;
}
getDetails() {
return 'Name: ' + this.name + '\nRoll: ' + this.roll_no;
}
}
var s1 = new Student('Arjun', 14, 'hello');
var result = s1.getDetails('Essay on Elephant');
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we learned about Constructors in Class, their syntax, and usage with examples.