Javascript Design Patterns: Constructor Pattern

Category : code

Date : March 24, 2016

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:

ES6 Implementation:

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!