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]) { ... }
- The constructor keyword is to declare a constructor method.
- The class can contain one constructor method only.
- JavaScript allows us to use the parent class constructor through the super keyword.
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