Javascript Class HowTo

June 3, 2008


Great Tutorial on Javascript Classes

function Person (firstname,lastname,age){
 
	this.firstname=firstname;
	this.lastname=lastname;
	this.age=age;
 
	this.introduction = function (type) {
		if (type=='simple'){
			alert("Hi, I am " + this.firstname +".");
		}else{
 
			alert("Hello, my name is "+this.firstname + " " + this.lastname+"." +
			 	" I am " + this.age + " years old.");
		}	
	}
 
}
 
var p = new Person("Hana","Daddy",30);
 
p.introduction("simple");
p.introduction();

Creating a Javascript class is just like creating a regular function. Two things to remember.

  • Use 'this' to access member variables.
  • How to define member functions

The above will show alert message dialog.
First, “Hi, I am Hana”.
Second, “Hello, my name is Hana Daddy. I am 30 years old.”.

Now by using prototyping, you can add additional functions to the predefined classes. Also all the initialized class objects instantly have access to the new function! That is very convenient.

//Prototyping : add 
Person.prototype.addAge = function (year) {
	if (year)
		this.age += year;
	else
		this.age +=1;
}
p.addAge(5);
p.introduction();

The new addAge function was called from the previously created Person object p. And it’s working without problem. The Dialog says “Hello, my name is Hana Daddy. I am 35 years old.”. 5 years more aged. Time surely flies.

Finally, inheritance is very simple, too. See below example.

// new Person inherited class
function GoodPerson(firstname,lastname,age){
	this.fromClass = Person;
	this.fromClass(firstname,lastname,age);
 
	this.characteristic="Good";
	this.doSomethingGood =  function (){
		alert("help others");
	}
}
 
var a = new GoodPerson("Good","Person",20);
a.introduction();

Thats about a all for the quick HOWTO on Javascript class. I will post my very very simple Ajax Javascript Class next time.

Share and Enjoy:
  • DZone
  • Twitter
  • Technorati
  • Reddit
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Diigo


Comments are closed.