Constructor method-tutorial
In JavaScript, a constructor method is used to create and initialize objects when you create an instance of a class.
Constructors help define the properties that each object will have and optionally accept parameters to customize these properties.
They are called automatically when you use the new keyword.
Syntax of Constructor Method
Example: Simple Constructor
Creates an object with fixed properties
Output
.webp)
Output
.webp)
Constructors help define the properties that each object will have and optionally accept parameters to customize these properties.
They are called automatically when you use the new keyword.
Syntax of Constructor Method
In ES6 classes, a constructor is defined inside the class using the constructor() method.
class ClassName { constructor(param1, param2) { this.param1 = param1; this.param2 = param2; }}
- ClassName: Name of the class (should start with uppercase by convention).
- constructor(): Special method to initialize object properties.
- this: Refers to the current object instance.
Example: Simple Constructor
Creates an object with fixed properties
<!DOCTYPE html><html>
<body>
<script> class Employee { constructor() { this.id = 105; this.name = "John"; } }
var emp = new Employee(); document.writeln(emp.id + " " + emp.name); </script>
</body>
</html>
Output
.webp)
Using super keyword
In JavaScript, when you create a subclass (child class) that extends a parent class, you can use the super() keyword to call the parent class’s constructor. This helps inherit properties from the parent class.
Example:
In JavaScript, when you create a subclass (child class) that extends a parent class, you can use the super() keyword to call the parent class’s constructor. This helps inherit properties from the parent class.
Example:
<!DOCTYPE html><html>
<body>
<script> class CompanyName { constructor() { this.company = "Quipoin"; } }
class Employee extends CompanyName { constructor(id, name) { super(); // Calls the parent class constructor this.id = id; this.name = name; } }
var emp = new Employee(1, "John"); document.writeln(emp.id + " " + emp.name + " " + emp.company); </script>
</body>
</html>
Output
.webp)
Key Point
- A constructor is called automatically when you create an object using new.
- constructor() is used to initialize object properties.
- Use super() inside a child class to call the parent class’s constructor and access parent properties.