JavaScript Constructor Method

To initialize and create an object in Javascript, a constructor method is used which is called when memory is allocated for an object. A class in Javascript can contain one constructor method only, however, a parent class constructor can be used by using the super keyword.

Example:

<!DOCTYPE html>
<html>
<body>
<script>
class Student {
constructor() {
this.firstname= "Mahesh";
this.lastname = "Kumawat";
}
}
var student = new Student();
document.writeln(student.firstname+" "+student.lastname);
</script>
</body>
</html>

JavaScript calls parent class constructor example:

<!DOCTYPE html>
<html>
<body>
<script>
class CollegeName
{
constructor()
{
this.college="NC College";
}
}
class Student extends CollegeName{
constructor(rollNo,name) {
super();
this.rollNo=rollNo;
this.name=name;
}
}
var stu= new Student(1,"Sue");
document.writeln(stu.rollNo+" "+stu.name+" "+stu.college);
</script>
</body>
</html>