CodesJava

Easy learning with example program codes

JavaScript Constructor Method

To initialize and for creating 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 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>

Example:

Mahesh Kumawat

JavaScript call 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>

Example:

1 Sue NC College
Please follow and like us:
error








Copyright © 2019 CodesJava DMCA.com Protection Status