A constructor function in JavaScript is a special function that helps us create and configure objects.
These functions act as “templates” that define the structure and behavior of the objects we will create.
Let’s see it with a basic example:
function Persona(nombre, edad) {
this.nombre = nombre; // Property name
this.edad = edad; // Property age
}
Here, Persona is a constructor function that defines an object with two properties: nombre and edad.
Creating an object with a constructor function
To create an object based on a constructor function, we use the new operator as follows:
const persona1 = new Persona("Luis", 30);
console.log(persona1.nombre); // "Luis"
console.log(persona1.edad); // 30
When we use the new operator:
- A new empty object is created.
thisinside the constructor function points to that new object.- The object is automatically returned at the end of the function (unless we explicitly return something different).
This flow allows the persona1 object to inherit the properties defined inside the constructor function.
Adding methods to objects
In addition to properties, we can add methods (functions associated with the object) inside constructor functions. For example:
function Coche(marca, modelo) {
this.marca = marca;
this.modelo = modelo;
this.detalles = function() {
return `Car: ${this.marca} ${this.modelo}`;
};
}
const coche1 = new Coche("Toyota", "Corolla");
console.log(coche1.detalles()); // "Car: Toyota Corolla"
In this case,
- The
detallesfunction is defined inside the constructor function - It will be available in all objects created with the
Cochefunction.
Classes as an alternative
Classes are a modern and more readable way to create objects, partially replacing constructor functions in JavaScript.
class Coche {
constructor(marca, modelo) {
this.marca = marca;
this.modelo = modelo;
}
detalles() {
return `Car: ${this.marca} ${this.modelo}`;
}
}
const coche1 = new Coche("Toyota", "Corolla");
console.log(coche1.detalles()); // "Car: Toyota Corolla"
Under the hood, classes use the same prototype mechanism. But the syntax is simpler to use.
