Member-only story
JavaScript’s class constructors are a powerful tool for creating objects with consistent properties and methods.
In this article, we’ll explore the fundamentals of class constructors, how to use them effectively, and provide up-to-date code examples to help you get started.
What are Class Constructors?
In JavaScript, a class constructor is a special method within a class that is used to initialize the object’s properties when an instance of the class is created. The constructor method is called automatically when you create a new object using the new
keyword. Here's a simple example of a class constructor:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I'm 30 years old.
In this example, the constructor
method is used to initialize the name
and age
properties of the Person
class. When we create a new Person
object using new Person('John', 30)
, the constructor is automatically called, and the object is initialized with the provided values.