Skip to content
Lydia Hallie theavocoder
Course contents
Complete JavaScript / Lesson 20

Function Constructors and Prototypes

Sometimes, you have to create many of the same types of objects. Let’s say that you need to somehow create new dogs in your app. A dog usually has the following features that are different for every dog:

  • Its name

  • Its color

  • Its size

  • Its breed

Let’s say that somehow we wanted to create a new dog every time using a regular object. That would look something like:

Function Constructors and Prototypes diagram 1

As you can imagine, this would get very repetitive and it’s a lot of code to write!

Instead, you can use a function constructor. In this case, that would look like:

Function Constructors and Prototypes diagram

We just created a function constructor called Dog. We create objects of the same type (dog type in this case) by calling the “new” keyword. If we now log dog1 or dog2 to the console, you’d see:

Function Constructors and Prototypes diagram 3

We just created an object without having to type the entire object over and over again! Awesome!

Prototype

One difference between a function constructor and a regular object, is that you can’t just add properties to the function constructor. For example:

Function Constructors and Prototypes diagram

Either, you have to write it in the function constructor itself, like:

Function Constructors and Prototypes diagram 5

Or, you add it to the prototype. For example:

Function Constructors and Prototypes diagram 6

We just added the property “age” to the prototype of the function constructor Person. So, what are the advantages of using the prototype instead? Imagine the following scenario, where every colored box represents a space in memory:

Function Constructors and Prototypes diagram 7

Right now, we didn’t use the prototype, but added the property directly to the constructor. This means that for every created object, a space in memory will be used in order to store the age property. Instead, when we use the prototype, it will only take up 1 space in memory where we can access it:

Function Constructors and Prototypes diagram 8

So, what exactly happens? First, the execution context creates a variable called this. When you use the keyword new, it depends what the this keyword refers to. When using new, it refers to the new empty object in memory. (Important, if you forget new, this refers to the global object) You’re now adding the name property to that empty object, as this property is on the Person constructor. The Person function is called the function constructor: it lets you construct objects and is invoked with the keyword new. If you don’t return anything from the function constructor, it will set its properties and methods. The object created by a constructor is called an instance of that constructor, and the creation of that instance is called instantiation.

References and further reading