Thursday, March 19, 2009

Javascript: Object Oriented Way

Brief
Javascript has features that enables you to write JavaScript code in OOP way. In this part I am not getting into details of OOP, understanding of OOP is prerequisite for this article. Javascript has implicit objects, for example arrays in JavaScript, Functions are objects and Objects are objects.

For example lets refer to a class called "Boxy". Objects of Boxy are like "div" to which you can add simple text or complex DOM.
Create a class

Boxy = function (/*String*/ id) {
this.id = id;
}

Above code is structure of function which can be used to create objects, object creation can be done
var boxy = new Boxy("boxy1");


Public and private

In above example id field has public access. Something like boxy.id = 1234;
Private access specifier is declared using the keyword var within the function. For example


Boxy = function (/*String*/ id) {
this.id = id;
var x =0;
var y=0;
}

vars and constructor parameters are private members.

Namespacing

This feature is not very popular yet. But if application is going to have loads of JavaScript for User interaction, this feature should be very handy. When multiple people are working on JavaScript, there is a possibility that same function name is used over and over again. This can be avoided to some extend by using namespacing.
My personal choice for choosing namespace follows Java way.
If you choose to have a namespace like com.xyz.boxy you would declare the name space as

if(!com) var com={};
if(!com.xyz) var com.xyz={};
if(!com.xyz.boxy) var com.xyz.boxy={};

Further you can have a function declared in this namespace as following

com.xyz.boxy = {
show: function () {
// do something interesting here
}
}

here com.xyz.boxy wraps a function called show. This function show can be invoked by com.xyz.boxy.show()

Pushing things little more lets consider the example below

if(!com) var com={}; // package
com = {
Boxy: function (name) { // class
this.boxyName = name; // public
var x=0,y=0; // private
this.getState = function() { // method
alert ("X, Y [" + x + "," + y +"]");
}
function generateHash = function () {
// do something about hash
}
}
}

1) Here we have a package called com.
2) The package com has Class/function Boxy
3) variables name, x and y are private variables
4) boxyName is a public variable.
5) function generateHash is a private function

Writing JavaScript in organized manner has several advantages and ease of readability is the foremost. A good thought over how to organize JavaScript would help in of maintenance of the code and make code more reusable.

0 comments:

Post a Comment