Javascript Design Patterns: Constructor Pattern

Date: March 24, 2016

Category : code

We will start with basic implementation of the constructor pattern even though it is not classified as an design pattern it has a unique value in javascript. There are no classes in JS as of ES5 but people regularly call many pattern as class and Constructor is one of them.

The constructor pattern enforces you to use new, even if you call the constructor like a function. In JavaScript, if the new keyword is forgotten, this will reference the global object inside the constructor, and that’s never a desirable situation.

ES5 Implementation:

{% gist 72d0c64438f62ce9d8ea %}

ES6 Implementation:

{% gist 93a77db81e75a56daa3a %}

ECMAScript 2015 (ES6) is obviously a lot cleaner but even if you write ES6 now using a transpiler your code will be converted into something a lot like our ES5 implemention using prototypes.

If you have any questions, comments or suggestions, feel free to join the discussion below!