Thursday, March 19, 2009

Javascript: Object Oriented Way

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) { = 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 = 1234;
Private access specifier is declared using the keyword var within the function. For example

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

vars and constructor parameters are private members.


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 you would declare the name space as

if(!com) var com={};
if(! var{};
if(! var{};

Further you can have a function declared in this namespace as following = {
show: function () {
// do something interesting here

here wraps a function called show. This function show can be invoked by

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.


Post a Comment