Object Oriented JavaScript Techniques

This post is in response to a couple of conversations I had with some friends around OOP in JavaScript. Over the last couple of months I have gotten really deep into the language with JQuery (which is a fantastic library by the way) so I thought I’d quickly list some techniques I have been using to structure my JavaScript code.

Creating a very simple class with an instance variable:
JavaScript has no concept of classes but they can be mimic-ed by creative uses of the Function object. So for example this is completely valid:

var vanillaFunction = function(){
	this.name = "vanilla"
}
var instance = new vanillaFunction();
alert(instance.name) //	vanilla


In the above case, “name” becomes an instance variable of the vanillaFunction class.

Constructing instance methods

var vanillaFunction = function(){
	this.name = "vanilla";
	this.sampleMethod = function(){
		return "SampleMethod was called";
	}
}

var instance = new vanillaFunction();
alert(instance.sampleMethod())

Under the hood whats going on is that the JavaScript interpreter is attaching the Function objects to the vanillaFunction’s prototype chain. So to add another function, we can append that function right on the prototype:

vanillaFunction.prototype.getName() = function(){
	return this.name; // returns "vanilla"
}

Note that these functions have access to the name instance variable defined in the main vanillaFunction class.

Creating class variables and methods (kinda):
Since all functions are essentially Objects, variables can be tagged on to the function object and then referenced as static class variables.


vanillaFunction.classVar = "some value here";

Same way, static functions can be created as well:

vanillaFunction.staticFunction = function(){
	alert("static function called");
}

However it should be noted that the static variables and methods do not have access to each other unless explicitly passed during invocation. Personally, I hardly ever use this and prefer static classes as shown below.

Creating Static classes:
A static class is one you can never create a new instance of. For example, instead of having static methods in a JavaScript class, you can create a static class by declaring your functions as variables on a pure JavaScript Object. This method can be used for example for creating a class of utility functions:

var utils = {
	trim:function(str, numCharacters){
		return str.substring(0, numCharacters);
	},
	
	log:function(msg){
		if(console){
			console.log(msg);
		}
	}
}
var s = utils.trim("Good day to you sir", 4);

Creating classes with JQuery
To create a class with JQuery, we use the jQuery.extend function which pretty much adds the instance methods to the prototype chain as we saw before:


MyClass = function(){
this.title = "MyClass";
};

$j.extend(MyClass.prototype, {
toString:function(){
return this.title;
}
});

Events:
Even though the ECMAScript specification defines events and how they work, they are not implemented consistently across browsers. The JQuery event system is much nicer since a) it works cross-browser and b) the event source doesn’t necessarily have to be a DOM element.


var obj = {name:"SimpleObj"};
jQuery(obj).bind("objectChanged", listener);
jQuery(obj).bind("objectChanged", listener);
jQuery(obj).trigger({type:"objectChanged"});

In the above example, we are binding to a custom event of type objectChanged. Usually, I access the event type as a static class variable:


var CustomEvents = {
OBJECT_CHANGED:"objectChanged";
}
jQuery(obj).bind(CustomEvents.OBJECT_CHANGED, listener);

That covers pretty much the basics oF OOP in JavaScript. A lot of metaphors (like private/protected/public accessors) may be missing here but I havent really found that to be too much of a problem. These metaphors have made my code a lot more manageable.

Further reading:
John Resig’s list of lessons in advanced JavaScript

Author: Arpit Mathur

Arpit Mathur is a Principal Engineer at Comcast Labs where he is currently working on a variety of topics including Machine Learning, Affective Computing, and Blockchain applications. Arpit has also worked extensively on Android and iOS applications, Virtual Reality apps as well as with web technologies like JavaScript, HTML and Ruby on Rails. He also spent a couple of years in the User Experience team as a Creative Technologist.

7 thoughts on “Object Oriented JavaScript Techniques”

Leave a comment