Archive for the 'Class' Category

20
Apr
07

Creating & Using Classes in Javascript

Well, many of us know that javascript is an object-oriented language, but actually using it can be quite tricky. What was interesting was the way you define classes in JS. For example if we want to define a class called “student” with name, id and major as variables, and getName(), getId(), and getMajor() as methods of the student object, this is what we need to do:


//contructor for our student class
function Student(name, id, major)
{
this.name = name;
this.id = id;
this.major = major;
}
//methods for our Student class
Student.prototype.getName = function()
{
return this.name;
}
Student.prototype.getId = function()
{
return this.id;
}
Student.prototype.getMajor = function()
{
return this.major;
}

Now, if we want to use our javascript Student class, this is what we do:


var newStudent = new Student("Ahsan", "003052040", "Computer Science");
alert(newStudent.getName()+ " " + newStudent.getId() + " " + newStudent.getMajor());

This should print the student information.




NOTICE:

I no longer maintain this blog. Please visit my new blog at http://ahsanity.com

My Book on CakePHP

If you are looking for a book to get started with CakePHP, then this book is definitely what you need :)
10% off at the publisher's site.

Blog Stats

  • 97,807 hits