A Journey with JavaScript Objects

**Disclaimer: This is on ES5 not ES6

When talking about different object oriented programming languages, you will mostly hear about Java, C++, Python, Ruby, etc. Most people however will not mention JavaScript. When I mention building classes in JavaScript to a Ruby programmer, they are surprised, almost every time, that this is doable. But it totally is. So, I want to take some time to explore from the ground up, different ways we can build objects and class like structures.

Object Literals

JavaScript supports the representation of associative arrays, and other simple data structures in the form of object literals. Usage of objects like this can be very powerful and are very common to use in JavaScript design patterns. They are also used in web services, inspiring the creation of JSON, which stands for JavaScript Object Notation. Below, I provide a basic example of this to show you how object literals can be used.

var album = {
"title" : "Blast Tyrant",
"band" : "Clutch",
"tracks" : {
"Regulator" : {
"length" : "5:29",
"rating" : 5
},
"The Ghost" : {
"length" : "4:38",
"rating" : 5
}
},
"release_dates" : [2004, 2011],
"tracks_as_objects" : [
{"name" : "Regulator"},
{"name" : "The Ghost"}
]
};

The above is just an example of an object being used to store data, but since functions are also objects that can be passed around, it is totally possible to start making interfaces, classes, and more with these.

JavaScript Design Patterns

So let’s talk a bit about what a design pattern is. Design patterns are blocks of code that developers use over and over again to solver similar problems. Specifically, we are going to look at the Revealing Module Pattern, and the Singleton Pattern.

JavaScript by nature does not support the native construction of classes like most programming languages would define a class. JavaScript by nature implements prototypal inheritance and won’t allow for the kind of structures we might be used with classical inheritance. Even ES6 and CoffeeScript, for all their merits, implement their features using the prototype system and syntactical sugar. It is because of this that developers have come up with patterns to mimic this kind of behavior.

The Revealing Module Pattern

The Revealing Module Pattern is a design pattern built around providing public and private functionality to a class like structure, which is something that JavaScript lacks natively. We accomplish this by building functions nested within a root function which returns an object with our public data and methods.

var Album = (function(newartist, newname, newtracks) {
var public_artist = newartist;
var private_tracks = newtracks;
var private_name = newname;

function public_getName() {
return private_name;
}

function public_setName(newname) {
if(typeof(newname) == 'string') {
private_name = newname;
}
else {
return 'name must be a string';
}
}

return {
getName:public_getName,
setName:public_setName,
artist:public_artist
};
})('Clutch', 'Blast Tyrant', ['Ghost', 'Regulator']);

console.log(Album.getName()); // 'Blast Tyrant'
console.log(Album.privateName); // undefined
Album.setName('Earth Rocker');
console.log(Album.getName()); // 'Earth Rocker'

The Singleton Pattern

The singleton pattern is used when you want the stand alone nature of a static class, but also have the ability to pass an object around. Typically, you only want only one instance of this class to exist. This could be used for making a database connection to avoid multiple connections that will affect performance, or possibly a shopping cart for an ecommerce website.

This works by having an automatically executing function set cart to a function that does the following.

var Cart = function() {
if (Cart.prototype._singletonInstance) {
return Cart.prototype._singletonInstance;
}

Cart.prototype._singletonInstance = this;

this.items = [];
this.setItem = function(item, qty) {
this.items.push({"item":item, "qty":qty});
};
};

JavaScript Prototypes

Now that we have taken a look at some of the ways developers mimic classic class based programming, let’s take a look at JavaScript’s native prototypal inheritance. All instances of a function share a single prototype object when created which prevents using more memory for redundant code. They also contain references to parent prototype objects. The previous examples work great, except when you need to create a large number of objects and have high performance. This is where JavaScript prototypes come it. You use them like so.

function Card(num, suit) {
this.num = num;
this.suit = suit;
}

Card.prototype.makeWild = function(new_num) {
this.num = new_num;
};

function Deck(suits, values, size) {
this.cards = new Array();
this.suits = suits;
this.values = values;
this.size = size
}

Deck.prototype.buildDeck = function() {
for(x=0; x<this.size; x++) {
var suit = this.suits[x % this.suits.length];
var num = this.values[x % this.values.length];
this.cards.push(new Card(num, suit));
}
};

Deck.prototype.printDeck = function() {
var response = "<ul>";

for(var x=0; x<this.size; x++)
{
var num = this.cards[x].num;
var suit = this.cards[x].suit;

response += "<li>" + num + " : " + suit + "</li>";
}

response += "</ul>";

return response;
};

Conclusion

There are many ways to handle object oriented design in JavaScript and many more than I have covered here. ES6 will do a lot to make this easier, but there will most likely still be places for these other data structures. Being able to get down to an object level and prototype level will give added flexibility when ES6 falls short of what we want.

Happy Coding!