Constructor Function
Constructor functions are a pre-ES6 pattern for creating objects. Modern JavaScript uses classes for the same purpose. You will see constructor functions in older codebases, so it is useful to understand how they work.
I. What is a constructor function?
A constructor function is a regular function that creates and initialises objects. You call it with the new keyword, which creates a new object, sets this to that object inside the function, and returns it automatically.
By convention, constructor function names start with a capital letter to distinguish them from regular functions.
II. Defining a constructor function
Pass the values you want to store as parameters. Inside the function, assign them to this.
function Person(name, birthDay, color) {
this.name = name;
this.birthDay = new Date(birthDay);
this.color = color;
}
Avoid using arrow functions for methods inside a constructor. Arrow functions do not have their own this, so they would not bind correctly to the new object.
III. Creating object instances
Call the function with new to create a new object:
const p1 = new Person("Anna", "3-25-1995", "green");
const p2 = new Person("Joe", "10-12-1990", "blue");
console.log(p1);
// Person { name: 'Anna', birthDay: Sat Mar 25 1995, color: 'green' }
console.log(p2.birthDay.getFullYear()); // 1990
new Date(string) turns a date string into a Date object. Useful Date methods include getFullYear(), getMonth(), getDate(), and getTime().
IV. Adding methods
You can include methods directly in the constructor body:
function Person(firstName, lastName, birthDay, color) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = new Date(birthDay);
this.color = color;
this.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
this.getBYear = function () {
return this.birthDay.getFullYear();
};
}
const p1 = new Person("Anna", "Wood", "3-25-1995", "green");
const p2 = new Person("Joe", "Hopkins", "10-12-1990", "blue");
console.log(p1.getFullName()); // Anna Wood
console.log(p2.getBYear()); // 1990
This works, but each new object gets its own copy of every method. Adding methods to the prototype instead means all instances share one copy. See Prototypes for that pattern.
V. Modern alternative
The ES6 class syntax does the same thing with cleaner code:
class Person {
constructor(firstName, lastName, birthDay, color) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDay = new Date(birthDay);
this.color = color;
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
getBYear() {
return this.birthDay.getFullYear();
}
}
const p1 = new Person("Anna", "Wood", "3-25-1995", "green");
console.log(p1.getFullName()); // Anna Wood
See Classes for more detail.