C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
JavaScript Constructor MethodA JavaScript constructor method is a special type of method which is used to initialize and create an object. It is called when memory is allocated for an object. Points to remember
Constructor Method ExampleLet's see a simple example of a constructor method.
<script>
class Employee {
constructor() {
this.id=101;
this.name = "Martin Roy";
}
}
var emp = new Employee();
document.writeln(emp.id+" "+emp.name);
</script>
Output: 101 Martin Roy Constructor Method Example: super keywordThe super keyword is used to call the parent class constructor. Let's see an example.
<script>
class CompanyName
{
constructor()
{
this.company="TheDeveloperBlog";
}
}
class Employee extends CompanyName {
constructor(id,name) {
super();
this.id=id;
this.name=name;
}
}
var emp = new Employee(1,"John");
document.writeln(emp.id+" "+emp.name+" "+emp.company);
</script>
Output: 1 John TheDeveloperBlog Note - If we didn't specify any constructor method, JavaScript use default constructor method.
Next TopicJS static Method
|