Course contents
- 01Variables
- 02Primitive Data Types
- 03Operators
- 04Conditionals
- 05Arrays
- 06Array methods and properties
- 07Objects
- 08Functions
- 09Callbacks
- 10Arrow functions
- 11Promises
- 12Async and await
- 13Loops
- 14DOM Manipulation
- 15Syntax parser
- 16Execution context and hoisting
- 17Call stack
- 18WebAPI and setTimeout
- 19Closures
- 20Function Constructors and Prototypes
- 21By value vs by reference
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:

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:

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:

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:

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

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

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:

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:

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
- MDN: Object prototypesHow objects inherit behavior.
- MDN: newWhat the new operator actually does.