Constructor Pattern (js)

Before es6, JavaScript doesn’t support the concept of classes but it does support special constructor functions that work with objects.

By simply prefixing a call to a constructor function with the keyword “new”, we can tell JavaScript we would like the function to behave like a constructor and instantiate a new object with the members defined by that function.

Inside a constructor, the keyword this references the new object that’s being created. Revisiting object creation, a basic constructor may look as follows:

Constructors With Prototypes

Functions, like almost all objects in JavaScript, contain a “prototype” object. When we call a JavaScript constructor to create an object, all the properties of the constructor’s prototype are then made available to the new object. In this fashion, multiple Car objects can be created which access the same prototype. We can thus extend the original example as follows:

Above, a single instance of toString() will now be shared between all of the Car objects.

Circular List example

In the example below, we declare a ListNode constructor function so that we can instantiate objects from it,

We instantiate different ListNode objects and link them together in constructor function List. The linking happens because each ListNode has a next and previous.

List has 4 public properties:
– head
– tail
– now
– listName

Head, tail, now all point to different parts of the list.

The list uses prototype functions insert, remove, display so users can enter, remove, and display data from the list.
Thus, all instantiations of constructor function List use these prototype functions.

https://stackoverflow.com/questions/24488196/revealing-module-prototype-pattern

PRO – This saves a lot of memory because say we create 2 List instantiations called metro and gallery. There will be 2 copies of these functions for each instantiation. However, if we are to use prototype, there is only 1 instance of all these functions. And both metro and gallery will call that 1 instance.

In other words, the benefit of the prototype is that its properties are shared amongst all instances. This means that it’s static, not instance-specific.

CON – If you want to use the prototype, you cannot access truly private variables; you will need to use public properties