A constructor method in JavaScript is a special method used to initialize and set up new objects created from a class. It is automatically invoked when an instance of the class is created. Here are the key points and examples to understand how constructors work
1. Declaration: The constructor keyword is used to declare the constructor method within a class.
2. Single Constructor: A class can contain only one constructor method. If you try to define more than one, it will result in a syntax error.
3. Inheritance: When using inheritance, the super keyword allows calling the parent class's constructor from the child class's constructor.
The basic syntax of a constructor method in a class:
class ClassName {
constructor(parameters) {
// Initialization code
}
}
<script>
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
document.write(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person1 = new Person('Alice', 30);
person1.greet(); // Output: Hello, my name is Alice and I am 30 years old.
</script>
When you create a class that inherits from another class, you use super to call the parent class's constructor.
<script>
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // Calls the parent class's constructor
this.breed = breed;
}
speak() {
document.write(`${this.name} barks.`);
}
}
const myDog = new Dog('Tommy', 'Labrador');
myDog.speak(); // Output: Tommy barks.
</script>
• Initialization: The constructor initializes properties and sets up default values when an object is created.
• Inheritance: The super keyword allows for extending classes by initializing the parent class's properties and methods.