Object Oriented JavaScript

This is an example of a neat way of handling classes in ECMAScript 5. ECMAScript 6 provides a way to handle classes natively which would thankfully make this trick redundant.

JavaScript is an object based prototypal language which raises some difficulties and peculiarities for how to write and design object oriented systems. Here is a basic treatment that discusses my preferred way to handle objects, pseudo-classes and hierarchies in JavaScript. My approach starts with the classic function prototypal style then adding some simple clear meta-programming we can use a much more declarative object style. This simple syntax makes working with JavaScript classes just a little bit sweeter have a peek:

Class style object instantiation with prototype

The defacto standard for managing constructor based object inheritance.

https://gist.github.com/ryardley/f52f9dceded74d14e102

Having to add dangling prototype assignments outside of constructors is a scattered way of dealing conceptually with what should be a unified entity, also, if you want to hide data privately one would have to use the parent scope which could be shared across objects limiting the point of hiding such information. Lets try to pull it all together with some simple syntactic sugar.

One better way to declare classes in JavaScript

https://gist.github.com/ryardley/06dd00cbde6d5f51b79d

The benefits of using this style of object programming are that the object is encapsulated within its own function scope whilst at the same time having a clear constructor as well as providing a place for declaring private closure variables that can act as member variables.

Now let me talk a little about how we get here...

Creating the Base with some meta-programming.

Use the following snippet to create a Base object:

https://gist.github.com/ryardley/f9c6ce80ea1c72318363

This allows us to use the following syntax to define classes:

https://gist.github.com/ryardley/fda5b4c4b45231a5034b

Conculsion

So presented here is a lighter and library free way to define classes in JavaScript. Hopefully with the advent of ES6 in the coming years, having to write your own meta-constructs like this for something as simple as object oriented programming will not be necessary. Now with tools such as Traceur becoming a standard option on bundlers such as webpack, this sort of thing could soon become a thing of the past but until then, and if you are using a system that is built without a transpiler, this is a nice lightweight way to get around some of the minor issues with Object Oriented JavaScript.

Rudi Yardley

Read more posts by this author.