Site icon i2tutorials

Javascript-Constructors

Javascript-Constructors

 

A JavaScript constructor method is a special type of method which is provided to initialize and create an object. This is called when memory is allocated for an object.

 

Syntax:

 

constructor([arguments]) { ... }

 

 

 Example:

 

<!DOCTYPE html>
<html>
<body>

<script>
class Employee {
 constructor() {
  this.id=21;
  this.name = "Student One";
 }
}
var emp = new Employee();
document.writeln(emp.id+" "+emp.name);
</script>

</body>
</html>

 

OUTPUT:

 

21 Student One

 

super keyword:

 

The super keyword is defined to call the parent class constructor.

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<script>
class CompanyName
{
 constructor()
 {
  this.company="i2tutorials";
 }
}
class Employee extends CompanyName {
 constructor(id,name) {
  super();
  this.id=id;
  this.name=name;
 }
}          
var emp = new Employee(1,"Student");
document.writeln(emp.id+" "+emp.name+" "+emp.company);
</script>

</body>
</html>

 

OUTPUT:

 

1 Student i2tutorials

 

 

Exit mobile version