07 November 2008

OOP in JavaScript : Class

The OOP (Object Oriented Programming) concept is really poor in JavaScript. Fortunately, it supports class concept, although the keyword 'class' is not used. 'function' keyword serves the purpose of 'class'. There are several ways to implement class. Here I'm showing the simplest one (in my opinion).

Creating Class:
The following code creates a Person class with 4 attributes[ name, father, mother & address] and 2 methods [getName() & setAddress(address)].

function Person(name, father, mother, address)
this._name = name;
this._father = father;
this._mother = mother;
this._address = address;

this.getName = function()
return this._name;

this.setAddress = function(address)
this._address = address;


  • The attributes are created and accessed through 'this' keyword.
  • Person function is the constructor of the class which takes 4 parameters.
  • The constructor (or function) can't be overloaded like C++ or Java.

Creating Instance (Object):
It's simple enough to understand from the following code.

var p1 = new Person("Ahona Saha", "Anup Kumar", "Snigdha Saha", "Bogra");
var p2 = new Person("Ananyo Mounota", "Asim Kumar Saha", "Aparna Saha", "Narsingdi");

Accessing Attributes and Calling Methods:
The attributes can be accessed like below-

Method calling is similar.

You can also change the attribute value.
p1._address = "Sariakandi, Bogra";

  • There is no Encapsulation in JavaScript i.e. any attributes is accessible from anywhere.
  • Interesting (and sometime disgusting) thing is, you can add attributes to an object anytime from anywhere (not necessarily from class). For example- if you want to add another attribute '_gender' with object p1, you can do it like below
    p1._gender = "female";



© 2007 t!ps n tr!cks: OOP in JavaScript : Class

Template unik dari rohman

---[[ Skip to top ]]---