Sobes.tech
Junior — Middle

Explain what a constructor function is in the context of object-oriented programming.

sobes.tech AI

Answer from AI

In object-oriented programming, a constructor function is a special function or method that is called when creating a new object to initialize its properties.

In JavaScript, for example, a constructor function is used to create objects using the new keyword:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person1 = new Person('Ivan', 30);
console.log(person1.name); // Ivan

Here, Person is a constructor function that sets initial values for a new object. In classes (ES6+), the constructor is defined through the constructor method.