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("Juan", 30);
console.log(persona1.nombre); // "Juan"
console.log(persona1.edad); // 30
When we use the new
operator:
- A new empty object is created.
this
inside 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 object persona1
to inherit the properties defined within the constructor function.
Adding methods to objects
In addition to properties, we can add methods (functions associated with the object) within 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
detalles
function is defined inside the constructor function. - It will be available on all objects created with the
Coche
function.
The problem with methods in the constructor
Although we can define methods inside a constructor function, there is a problem: each created object will have its own copy of the method. This is inefficient if we create many objects.
A better practice is to use the prototype to share methods among all objects created by the constructor function.
function Coche(marca, modelo) {
this.marca = marca;
this.modelo = modelo;
}
// Shared method on the prototype
Coche.prototype.detalles = function() {
return `Car: ${this.marca} ${this.modelo}`;
};
const coche1 = new Coche("Toyota", "Corolla");
const coche2 = new Coche("Honda", "Civic");
console.log(coche1.detalles()); // "Car: Toyota Corolla"
console.log(coche2.detalles()); // "Car: Honda Civic"
Here, the detalles
method resides on the Coche
prototype and is not duplicated in each object.
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 easier to use.