The constructor pattern is arguably the bread and butter design pattern. Some context: JavaScript is a so-called classless, inheritance is instead prototypal: objects inherit from objects. This particular feature of the language was originally inspired by Self. With this in mind, we try to mimic class-like inheritance using objects - in particular we want to create object constructors.
To start, all we need to bear in mind is some basic JavaScript syntax,
- We can append key to objects using the “dot” syntax,
- We create a new object instance using the
new
keyword.
The pattern usually follows,
- Use a function closure to create an object-like structure, this is our “constructor function,”
- Append variable values to an object instance using the
this
keyword, - Append shared object methods to the Prototype object.
Altogether we would get something,
Though simple in its execution, depending on the nature of the problem at hand the constructor pattern could lead to a lot of unnecessary bloat. In the coming weeks, we will see constructors again and again in some form or another, as they often form a smaller part of more elaborate patterns.
All the best,
Tom