google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank
Guest, register






Object Oriented JavaScript Techniques This article will show you some OOP elemtary techniques in JavaScript, for example: creating classes, constructing instance methods, declare variables and methods,...


Label: Object Oriented JavaScript, technique, OOP, elemtary, class, instance, method, variable

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

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.

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web