Constructor in JavaScript
In this tutorial, we will learn about constructors in JavaScript.
The constructor is a special method in JavaScript that is used to initialize objects. It is called when an object is created. The constructor method is defined using the constructor keyword.
The constructor method is used to set the initial values of an object. It is called automatically when an object is created using the new keyword.
Here is an example of a constructor method using the class syntax:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let person = new Person("John", 30);
console.log(person.name); // Output: John
console.log(person.age); // Output: 30In the above example, we have defined a Person class with a constructor method that takes two parameters name and age. The constructor method initializes the name and age properties of the object.
When we create a new Person object using the new keyword, the constructor method is called with the specified arguments.
The constructor method can also be defined using the function syntax:
function Person(name, age) {
this.name = name;
this.age = age;
}
let person = new Person("John", 30);
console.log(person.name); // Output: John
console.log(person.age); // Output: 30In the above example, we have defined a Person function that acts as a constructor. When we create a new Person object using the new keyword, the function is called with the specified arguments.
Conclusion
- The constructor is a special method in JavaScript that is used to initialize objects.
- The constructor method is defined using the
constructorkeyword. - The constructor method is called automatically when an object is created using the
newkeyword. - The constructor method can be defined using the
classsyntax or the function syntax. - The constructor method is used to set the initial values of an object.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on