Intro to JavaScript constructor functions

Constructor functions in JavaScript help us create new objects with similar properties and behaviors (methods), without the need to set them up one by one. This makes life much easier and less repetitive, especially when we need to work with lots of data that is stored in objects.

The basics

When using a constructor function as a template for your new object, the initial rules to follow are quite simple:

  • capitalize the function name’s first letter so it can be distinguished from other functions that are not constructors
  • don’t use an arrow function to define your constructor function, but use the function keyword instead

A very simple constructor function will look like this:

function Bird() {
this.name = name;
this.color = color;
}

Don’t be confused by the use of this here. While the topic of this is too much to cover in this post, we’ll get to its use in constructor functions in a bit. Before that, note the last rule basic rule in the context of constructor functions:

  • call a constructor function with the keyword new to create a new instance of the object

We have our Bird function above which provides us with a template to create all kinds of Bird objects now. We simply pass it the parameters it expects:

let swan = new Bird('Swan', 'white');

let crow = new Bird('Crow', 'black');

With the code above, we have just created two new Bird objects, one that is swan where this.name has the value of ‘Swan’ and this.color has the value of ‘white’; and one that is crow with ‘Crow’ as the value of this.name and ‘black’ as the value of this.color. To be precise, the swan and crow objects are instances of the Bird constructor.

As mentioned above, one of the most important things to remember about constructor functions is that they define properties and behaviors. Their main use is not to return values as others functions do (even though it is possible to add a return statement to your object) .

The use of this

Ah, our beloved this. It rings every new programmer’s alarm as soon as it appears, right? Inside of constructor functions, this refers to the new object it will create and sets its properties. Referring back to the example code above, this means that this.name refers to the name property that will be created in the new instance of Bird.

Determining instances

We can use the instanceof operator to determine whether or not an object was created with a constructor. It will return true or false. Using the example code from above once more:

let Bird = function (name, color) {
this.name = name;
this.color = color:
}
let swan = new Bird('Swan', 'white');

swan instanceof Bird; // true

let penguin = {
name = 'Pengu',
color = 'white'
}
 penguin instanceof Bird // false

1 comment

Leave a comment

Your email address will not be published. Required fields are marked *