Creating Multiple Objects with Constructors
In the previous examples, you created one object with its properties and methods. How would you create more than one? Constructors
. Constructors allow you to create as many objects as you like. This article explains how to use the new
keyword and run constructors in JavaScript programs.
Using object literals is fine when you only need to create one
object, but if you have to create more than one, as in the previous
section, they're seriously inadequate. We have to write out the same
code for every object we create, and if we want to change some
properties of the object - like adding a height
property - then we have to remember to update every object.
We would like a way to define the "shape" of an object - the set of methods and the properties it can have - and then create as many objects as we like, just updating the values for the properties that are different.
The first version of this is just a function:
function createPerson(name) { const obj = {}; obj.name = name; obj.introduceSelf = function () { console.log(`Hi! I'm ${this.name}.`); }; return obj; }
This function creates and returns a new object each time we call it. The object will have two members:
- a property
name
- a method
introduceSelf()
.
Note that createPerson()
takes a parameter name
to set the value of the name
property, but the value of the introduceSelf()
method will be the same for all objects created using this function. This is a very common pattern for creating objects.
Now we can create as many objects as we like, reusing the definition:
const salva = createPerson("Salva"); salva.name; salva.introduceSelf(); // "Hi! I'm Salva." const frankie = createPerson("Frankie"); frankie.name; frankie.introduceSelf(); // "Hi! I'm Frankie."
This works fine but is a bit long-winded: we have to create an empty
object, initialize it, and return it. A better way is to use a constructor. A constructor is just a function called using the new
keyword. When you call a constructor, it will:
- create a new object
- bind
this
to the new object, so you can refer tothis
in your constructor code - run the code in the constructor
- return the new object.
Constructors, by convention, start with a capital letter and are named for the type of object they create. So we could rewrite our example like this:
function Person(name) { this.name = name; this.introduceSelf = function () { console.log(`Hi! I'm ${this.name}.`); }; }
To call Person()
as a constructor, we use new
:
const salva = new Person("Salva"); salva.name; salva.introduceSelf(); // "Hi! I'm Salva." const frankie = new Person("Frankie"); frankie.name; frankie.introduceSelf(); // "Hi! I'm Frankie."
Source: Mozilla, https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#introducing_constructors
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.