How do you create a constructor function?
Creating a constructor function
A constructor function in JavaScript is a special function used as a template to create and initialize objects. When you want to create multiple objects that have the same structure—meaning the same properties and methods—you can define a constructor function once and then use it to generate as many of those objects as you need.
How to Create a Constructor Function
There are two main conventions to follow when writing a constructor function:
- The function name starts with a capital letter (e.g.,
Person
, notperson
). This is a standard practice that signals to other developers that the function is intended to be used with thenew
keyword as a constructor. - It uses the
this
keyword to assign properties and methods to the object that will be created. Thethis
keyword inside the constructor refers to the new object being formed.
Here is a basic example of a constructor for Person
objects:
function Person(firstName, lastName, age) {
// 'this' refers to the new empty object being created
// Assign properties to the new object based on the arguments passed in
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
This constructor function defines a template for objects that will have firstName
, lastName
, and age
properties.
How to Use a Constructor Function
Once you have defined the constructor function, you can create new objects from it. To do this, you use the new keyword followed by a call to the constructor function with the required arguments.
// Create two new objects using the Person constructor
const person1 = new Person('Alice', 'Smith', 30);
const person2 = new Person('Bob', 'Johnson', 25);
// Let's inspect the created objects
console.log(person1);
// Output: Person { firstName: 'Alice', lastName: 'Smith', age: 30 }
console.log(person2.firstName);
// Output: Bob
What does the new
keyword do?
When you use the new keyword, JavaScript performs four steps in the background:
- Creates a new, empty object (like
{}
). - Links this new object to the constructor function's prototype. This allows the new object to inherit properties and methods from the constructor's prototype.
- Executes the constructor function. The
this
keyword is set to point to the new object, so properties are added to it as defined in the function. - Returns the new object. If the constructor function doesn't explicitly return another object, the newly created object is returned automatically.
Adding Functions (Methods) to Objects
Objects typically have not only data (properties) but also behavior (methods). Let's add a method to our Person objects.
Method 1: The Simple (but less efficient) Way
You can add a function directly inside the constructor.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.sayHello = function () {
console.log('Hello, my name is ' + this.firstName);
};
}
const person1 = new Person('Alice');
person1.sayHello(); // Output: Hello, my name is Alice
The Problem: This approach is inefficient. Every single object created with new Person()
will get its own separate copy of the sayHello
function. If you create 1,000 person objects, you also create 1,000 separate function objects that all do the exact same thing. This consumes more memory than necessary.
Method 2: The Better Way using prototype
Every constructor function in JavaScript has a special property called prototype
. The prototype
is a shared object, and any properties or methods added to it are available to all objects created by that constructor. By adding methods to the prototype, you ensure they are only stored once in memory.
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Add the method to the Person's prototype
Person.prototype.getFullName = function () {
return this.firstName + ' ' + this.lastName;
};
const person1 = new Person('Alice', 'Smith');
const person2 = new Person('Bob', 'Johnson');
console.log(person1.getFullName()); // Output: Alice Smith
console.log(person2.getFullName()); // Output: Bob Johnson
Now, both person1
and person2
can use getFullName()
, but the function itself is stored in only one location (the Person.prototype
object). This is the standard and most memory-efficient way to define methods for constructed objects.
Summary
- A constructor function is a function used to create and initialize objects.
- Its name should start with a capital letter by convention.
- It uses the
this
keyword to define the properties of the objects it will create. - You must use the
new
keyword to create new objects (instances) from the constructor. - For better performance and memory efficiency, methods should be added to the constructor's
prototype
.