Constructor Pattern in JavaScript

August 25, 2021 · 3 min readLucian Ciobanu
Tags:JavaScript

I'm trying to improve my JavaScript know-how so I'm looking into finding out more about commonly used design patterns in JavaScript. The first one I came across is the constructor pattern.

Before getting to an example, I've found a very interesting way to define a property on JavaScript objects as such:

var task = {
  title: 'My task',
  description: 'My description'
}

Object.defineProperty(task, 'toString', {
  value: function() {
    return this.title + ' ' + this.description;
  },
  writable: true,
  enumerable: true,
  configurable: true
});

In object task I'm defining property 'toString' which has as value a function and I'm also passing optional properties like "writable" which allows for this property to be overwritten, "enumberable" which allows for the property to be displayed in the Object.keys array and "configurable" which allows me to update these properties later on if I need to.

The following code snippet shows how I can create a constructor for tasks:

var Task = function(name) {
  this.name = name;
  this.completed = false;
}

//using prototype to define properties which will be
//available on any of the new created objects
Task.prototype.complete = function() {
  this.completed = true;
}

var task1 = new Task('create demo');
var task2 = new Task('write new blog post');

task1.complete();
task2.complete();

Both of objects task1 and task2 will have the complete property.

In ES2015, we have the class concept introduced and we can use it as such to obtain the same result as above:

//use strict is needed for node
'use strict'

class Task {
  constructor(name) {
    this.name = name;
    this.completed = false;
  }
  complete() {
    this.completed = true;
  }
}

var task1 = new Task('create demo');
var task2 = new Task('write new blog post');

task1.complete();
task2.complete();

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery