Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

Using the revealing prototype pattern in JavaScript

Posted: January 30, 2016
Written by: Saints At Play
Category: Javascript

When developing applications with JavaScript you quickly realise the need to architect and structure your code in a way that's modular, scalable and efficient.

Due to JavaScript's flexibility there are many ways this could be achieved; some better than others.

In this article we're going to take a look at how this could be achieved using the revealing prototype pattern and discuss the benefits and drawbacks of this particular design pattern...

Wait a minute...what's a design pattern?

The following was covered in a previous article but it merits being repeated for those who may not be familiar with the term.

A design pattern is simply an agreed solution for a particular coding problem or set of problems that can help with the following:

  1. Is re-usable
  2. Is proven to work
  3. Provides an agreed structure and vocabulary
  4. Helps avoid code repetition
  5. Allows developers to compose elements and relationships between elements within their code more efficiently

The architect Christopher Alexander is credited with developing design patterns in the late 1970's and the term was later applied to software design in the 1990's by the Gang of Four (Erich Gamma, John Vlissides, Ralph Johnson and Richard Helm).

A design pattern can fall into one or more of the following categories:

  • Creational (handles/controls object creation)
  • Structural (handles the composition of and relationship between objects)
  • Behavioural (handles the communication between objects in a system)

Some of the different types of design patterns commonly used in software design (regardless of the programming language) are as follows:

There are, however, many different design patterns but, for the purpose of this article, we are only interested in the revealing prototype pattern and how that applies to developing JavaScript applications.

JavaScript and prototypes

Before we start to investigate this pattern we first of all have to understand the JavaScript language itself.

JavaScript is a prototype based programming language which means that behaviour reuse, otherwise known as inheritance, is performed through cloning existing objects to serve as prototypes. In practice this means that all objects in JavaScript are linked through a property called prototype. This prototype contains inherent methods and properties inherited from the native Object prototype (its parent if you will).

When a new object is created then that object inherits the native methods and properties of the prototype object. This means that when we create custom objects in our scripts then these objects already have native methods associated with them by default.

If we then create instances of this custom object the prototype property will have access to not only the native methods mentioned above but also any methods we declared in our original parent object too. This makes inheritance a de-facto rule in prototype based languages and is a very powerful tool that we can exploit to make our applications more efficient.

Now let's explore the revealing prototype pattern itself.

The revealing prototype pattern

Similar to the revealing module pattern this design pattern provides the following benefits for architecting and structuring application code:

  • Allows emulation of private access modifiers in JavaScript
  • Provides a consistent and clean separation between private and public modifiers
  • Avoids global namespace pollution through localisation of variables and methods via closures
  • Provides a consistent structure for code
  • Highly readable solution for developing code

In addition to the above the revealing prototype pattern offers the following:

  • Reduced memory allocation as a result of shared methods and properties with each new instance of an object being created
  • Classes can be extended but not modified; this means functionality can be added without affecting any existing implementation

Now let's see what the revealing prototype pattern might look like when implemented in practice.

In the following example we've created a very basic validation class that can be used to validate forms used on a website:

function Validation()
{
  this.stringExprTest   = /.+/; 
  this.emailExprTest    = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
  this.numberExprTest   = /^(0|[ 1-9][ 0-9]*)$/;
};


Validation.prototype 	= 	(function()
{


  var _validateString 	=	function(str)
  {
	return this.stringExprTest.test(str);
  },


  _validateNumber 	=	function(num)
  {
	return this.numberExprTest.test(num);
  },


  _validateEmail 	=	function(email)
  {
	return this.emailExprTest.test(email);
  };


  return {
	validateString 	: 	_validateString,
	validateNumber 	: 	_validateNumber,
	validateEmail 	: 	_validateEmail,
  };


})();

Experienced JavaScript developers will notice that the above class bears many similarities with the revealing module pattern although there are some significant differences to be aware of:

  1. Use of function constructor to declare class
  2. Use of prototype constructor to encapsulate method declarations
  3. Variable constants declared in constructor function - with the this keyword - which can be inherited by prototype methods

So how would this be used?

Implementing the revealing prototype pattern

Assuming we have taken the above class, placed this into a separate JS file and then called this script inside a basic HTML page we could test our class in the browser console like so:

// Initialise our class
var validate 	= 	new Validation();

If we, immediately afterwards, then type validate into the console we are shown an object tree revealing the prototype chain of methods and properties:

Object prototype chain in JavaScript

In the above screenshot, tested in Safari, you can see the object tree displaying (in order from top to bottom):

  • Class constructor properties
  • Instance methods (developer created)
  • Object prototype properties (inherent to JavaScript)

This is a great way to see what the objects we create are actually inheriting and also clearly demonstrates the inheritance of both native JS and instance (the ones we as developers create) methods.

And what about testing the methods associated with our object?

Simple:

validate.validateEmail("john.doe@googlemail.com");
// Returns true 

validate.validateEmail("john.doe@googlemail");
// Returns false 

Not too challenging huh?

This all sounds great but...

What are the drawbacks to using this design pattern?

Depending on your perspective you may find the following to be disadvantages of this particular solution:

  • Class contructor and prototype definition are implemented separately
  • Object has to be declared through use of new keyword - no auto-invoking unlike revealing module pattern
  • Inability to access private members (this might be an issue with unit testing for example although it can be argued that if you need to test a private variable/method then it should probably be public anyway)
  • Difficult to fix bugs with public methods if they are referred to as different methods privately
« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.