In JavaScript, a class constructor is a special method in a class that is called when an object is created from the class. It is used to initialize the object's properties and set the initial state of the object.
Here is an example of a simple class constructor in JavaScript:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
In this example, the Person
class has a constructor that takes two arguments, name
and age
. When a new Person
object is created, the constructor is called, and the name
and age
properties are set.
For examples:
let person = new Person('John', 30);
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
Here are some key points about class constructors in JavaScript:
- The constructor is called when an object is created from the class using the
new
keyword. - The constructor is responsible for initializing the object's properties.
- The constructor can take arguments, which are passed when the object is created.
- If no constructor is defined, a default constructor is created automatically.
Here are some more examples of class constructors in JavaScript:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
}
let car = new Car('Toyota', 'Corolla', 2020);
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
let point = new Point(10, 20);
Top comments (0)