Object Creation … The constructor pattern

One common way that objects are constructed in JavaScript is the constructor pattern.

In JavaScript, any function can return an Object. So a constructor is really just a function, but there are two things that make a constructor function special.

  • The new keyword in front of the function call
  • A capital letter in the function definition ( convention )

The new keyword does four things.

  1. It creates a brand new empty object ( {} ).
  2. The created object gets [[Prototype]] linked.
  3. The created object is set to this.
  4. This (the newly created object) is automatically returned from the constructor function. Unless it explicitly returns another object (not sure why you would do this).

In the above example the properties name and age are set to the new object that gets returned by the constructor function, which is preceded by the new keyword.

Before we start talking about adding behavior to these Person objects we have to talk about number 2 on the new keyword list. The new keyword creates a Prototype linkage. All objects have an internal prototype property, which is essentially a link to another object.

Each time we create a new Person, that new instance of Person gets linked to the Person.prototype. Lets look at this with an example.

Because every time we create a new instance of Person we also create a link to the Person prototype, we can attach our methods directly to the prototype.

When p1.greeting() is called, JavaScript looks to p1 and asks “is there a greeting method here?”

Since there is no greeting method directly on p1, JavaScript will proceed up the prototype chain to find the greeting method. Both instances p1 and p2 will have access to the greeting method, or any method we define on Person.prototype.

The greeting method is only ever declared once. Each new instance is referencing the same method. We can say that each instance is delegating to the Person prototype.

This is how the language is built. The reason you can use array methods such as map, filter and reduce for example, is because they exist on Array.prototype. You don’t need to define a new map method everytime you create an array!

And there is it… you now know a little more about the constructor pattern. Thanks for taking the time!