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,...


Sampled by © JavaScriptBank.com

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.

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
Insights for Advanced Zooming and Panning in JavaScript Charts
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website


Top view articles
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
Top 10 Beautiful Christmas Countdown Timers
Top 10 Best JavaScript eBooks that Beginners should Learn
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com