A constructor function in JavaScript is a special type of function that is used to create objects. Constructor functions are defined using the function keyword, but they have a special syntax that distinguishes them from regular functions.
The syntax for a constructor function is as follows:
function constructorName(parameters) {
// Body of the function
}
The constructorName is the name of the constructor function. The parameters are the values that are passed to the constructor function when an object is created. The Body of the function is the code that is executed when the constructor function is called.
When a constructor function is called, it creates a new object and assigns the values of the parameters to the properties of the object. The constructor function can also set the values of properties that are not passed as parameters.
The following code defines a constructor function called Person() that creates a new object representing a person:
function Person(name, age) {
this.name = name;
this.age = age;
}
The Person() constructor function takes two parameters: the name and age of the person. The this keyword refers to the newly created object. So, the expression this.name refers to the name property of the object, and the expression this.age refers to the age property of the object.
The Person() constructor function can be used to create new objects representing people. The following code creates a new object representing a person named John Doe who is 30 years old: