Using Classes in JavaScript
From a developers point the internet is a buzz with terms such as web 2.0, AJAX, JSON, and DHTML. What do these terms have in common: JavaScript. In concept Web 2.0 web sites uses Dynamic HTML to make the web sites more interactive for the users. This can be achieved in part using the patterns of Asynchronous JavaScript and XML (AJAX) or JavaScript Object Notation (JSON). The intent of this article is not to describe these concepts and patterns but to prove that JavaScript is fully capable of being developed in true Object Orientated Programming (OOP) style with classes.
JavaScript being the versatile scripting language that it is makes it easy enough to just pop in a function or two to control an aspect of a application, but as development or growth continues these “just a couple” of functions may turn into a hundred plus functions. It is this ability write procedural coding that makes JavaScript a language both an easy to learn language by not needing to understand OOP concepts and application development fast with the “just a few” functions.
However it is the procedural coding that makes JavaScript a high maintenance coding language as well. When writing this way there is so many things that need to be kept in your mind: variable naming to prevent overwriting with a bad value from a completely different function; function naming as the last loaded function will take effect over a previously loaded same name function; after the first hundred or so functions code maintenance can become high.
So in comes Object Orientated Design for JavaScript Classes!
To start off let’s define what a class is and why it’s beneficial. A class is an object and JavaScript is full of objects: Array; Date; document; etc. A class has encapsulation, meaning that it holds: attributes; properties; methods which can be public, shared or private. A class acts upon it and with others but does not know how the other objects works, and doesn’t particularly care. A lot less thought is needed to write classes; I mean you don’t have to worry that much about overwriting the global variables, function name overwriting, and a whole slew of other considerations. Development is faster because classes can interact to make compound classes. To follow along you can view the proof of concept examples at: http://www.techraving.com/JavaScriptClasses.html
No special functions to make JavaScript Classes just use the Scope Chain and this!
I won’t go into a lot of detail on how the scope chain works; it’s important to know but lengthy and I’m sure you want to get to the meat of how classes are built. In a nutshell keep in mind that the scope chain means a variable or function is available to any variable or function declared in the same scope or immediately below it. Additionally the keyword this makes public an encapsulated function or variable. Not only is it used to make public but also as a pointer to the internal private method of the class.
Here’s an example:
function scopeLevel1 () {
var scopeLevel1var = “Hello World”;
//scopeLevel1var = scopeLevel2var; // Not correct since scopeLevel2var is created below the scope chain;
scopeLevel2 (); // Available since it is at the same scope level
//scopeLevel3 (); // Not Available since it is a function of scopeLevel2() PS Uncomment and only scopeLevel2() runs then it dies
ScopeLevel4(); // Is available since ScopeLevel2 points by using this keyword
function scopeLevel2() {
var scopeLevel2var = scopeLevel1var; //This is available since scopeLevel1var was created above
this.ScopeLevel4 = scopeLevel4;
scopeLevel3(); // Available since it is in same scope
function scopeLevel3() {
var scopeLevel3var = “World”;
alert(”scopeLevel3: ” + scopeLevel2var);
}
function scopeLevel4() {
//alert(”scopeLevel4: ” + scopeLevel3var); // Not Avail since scopeLevel3var is not in the same scope or immediately below and will kill script if used
alert(”scopeLevel4″);
}
alert(”scopeLevel2: ” + scopeLevel2var);
}
alert(”scopeLevel1″);
}
Off to class! Figuratively but not literally.
To follow along the final class object FirstClass and the test files are located at . So let’s begin!
First, in the usual way of creating a function object we need to declare a function and let’s call it FirstClass.
function FirstClass() {
}
Yes this looks like a function but try calling var FirstClassObj = new FirstClass(); and then do a typeof FirstClassObj and see that it is now an object! This is because assigning a function to a variable makes that function an object. Thus the first step in FirstClass as a class.
What just happened! When you assign a variable a function what happens is that the function is created as an object or in other words instantiated. From this point on you will call the FirstClass methods by using the variable reference FirstClassObj.
Think about how you reference JavaScript intrinsic functions:
var someArrayObj = new Array();
alert(someArrayObj.length);
You see that length is a public method of Array() but you must instantiate it first to a variable.
Me, Myself and I!
The strength of classes in JavaScript is that internal attributes and methods are by default private, remember scope chain. With this ability it’s easy to prevent any uncontrolled assignment to an internal variable or use of an internal method incorrectly.
To create private attributes and methods declare them under the scope of FirstClass().
function FirstClass() {
var _MyFirstPrivateAttribute;
function myFirstPrivateMethod(value) {
_MyFirstPrivateAttribute = value;
}
}
What Just Happened! Keeping scope chain in mind what we did was create MyFirstPrivateAttribute and myFirstPrivateMethod under the scope of FirstClass. This means that FirstClass has complete use to these but nothing above scope of FirstClass can make use of these even assigning an instance of FirstClass to a variable. In other words:
var FirstClassObj = new FirstClass();
FirstClassObj.myFirstPrivateMethod(“SomeValue”);
This will fail because myFirstPrivateMethod is not public.
Me, Myself and You!
It is now time to let our budding class be used in an app as a completely private class is very specialized indeed. The ability to make an attribute or method public surrounds the use of the “this” keyword.
function FirstClass() {
var _MyFirstPublicAttribute;
var _MyFirstPrivateAttribute;
This.MyFirstPublicAttribute = _MyFirstPublicAttribute;// Not a good idea
This.MyFirstPublicMethod = myFirstPublicMethod;
function myFirstPublicMethod(value) {
_MyFirstPrivateAttribute = value;
myFirstPrivateMethod();
}
function myFirstPrivateMethod() {
alert(_MyFirstPrivateAttribute;);
}
}
What Just Happened! By using the keyword this on MyFirstPublicMethod you are in essence attaching an object to FirstClass which runs function myFirstPublicMethod. If you are familiar with the prototype in JavaScript you can also substitute this with FirstClass.prototype.MyFirstPublicMethod = myFirstPublicMethod;
You’ll also note that I did declare a public attribute. This not a good idea since anything can change the value. In order to maintain OO programming we really need to have setter and getters for this attribute. This way we can control what is allowed or dis-allowed as a value.
function FirstClass() {
var _MyFirstPrivateAttribute;
var _MySecondPrivateAttribute = “I’m a Class”;
this.SetMyFirstPublicMethod = setMyFirstPublicMethod;
this.GetMyFirstPublicMethod = getMyFirstPublicMethod;
//The keyword this can be substituded with (objectName).prototype
FirstClass.prototype.GetMyFirstReadOnlyAttribute = function() { return _MySecondPrivateAttribute; }
function setMyFirstPublicMethod(value) {
if (typeof value == “string” ) {
_MyFirstPrivateAttribute = value;
}
}
function getMyFirstPublicMethod () {
return _MyFirstPrivateAttribute;
}
}
So notice that there are now setters and getters to the FirstClass that change or return the MyFirstPrivateAttribute and even make sure that it is a string (or depending on what you require). You certainly do not need ssetters or getter or can have only one of each for any attribute. That is what I did for the MySecondPrivateAttribute, although it’s a shortcut. You are completely allowed inline scripting such as function() { return MySeconPrivateAttribute; }
Me, You and Friends!
When I first figured out how to make classes I immediately set about refactoring(recoding) my JavaScript libraries. I came to one library that required all twelve months as classes be feed to an array after which I index the month name. To my dismay every array index of all twelve months returned December.
Thus was found that object classes posses shared attributes between same object types. This is what protected, friend, shared type attributes are to such languages as C++, C#, Java. It can be very useful to have shared attributes as changing an attribute in one class reflects immediately in all the other same class objects. The pitfall to remember is that when you instantiate a new class your shared attribute will be reset the default value.
function Customer() {
var _ClassName = “Customer”; //Private Attribute
_ClassVersion = “1.0″; //Shared attribute between same objects
this.SetClassName = function(value) { return _ClassName = value; }
this.GetClassName = function() { return _ClassName; }
this.GetVersion = function() { return _ClassVersion; }
this.SetVersion = function(value) { _ClassVersion = value; }
}
What Just Happened! Remember when I said all the values of the months where December? So what caused the shared attributes? Did you notice the lack of var before ClassName and Count? When using var while creating a variable you are declaring that this variable is only to be used within this instance of the function or object. By not using the var keyword you are allowing all objects of the same type to use this variable. Hence shared attributes are born.
So there you have it!
Now you have all the ingredients to go out and make your own JavaScript OOP classes. The scope chain means that any function on the same level or immediately below it has access to use and all variable within the function on down. The keyword this attaches a public object to the class that points to the internal function of the class. Using the keyword var means the difference of having a private or shared attribute between objects of the same class.

