Wednesday, April 05, 2006

Object and their methods in Javascript

I've been looking around to find a really nice way of defining classes and their methods in JavaScript. I am aware that there are numerous libraries out that have defined their own syntax for defining classes and their methods etc. However, my quest was to find a solution that did not require any extra libraries.

I'll explain it with an example;

function Student(name){

this.name = name;

/*toString method of student class */
Student.prototype.toString = function (){
return "My name is " + this.name;
}
}

The example outlines a very basic "Student" class that has a 'name' property and a 'toString' method. Since properties and functions are both objects in Javasctip we can define a class using the function keyword. It basically involves defining a constructor for the class. Since the "Student" class takes in 'name' as an argument, the "Student" class can be instantiated as;

studentObj = new Student("Bob");

The "Student" class also contains a method called 'toString'. The method is assigned to Student.prototype to ensure that there is only a single copy of the method for each instance. I found an About.com artitle, which suggested that this.prototype.toString = function() {} is the right syntax. However, it does not work with Firefox. Firefox complains about prototype not having any properties.

Once an instance has been created its methods or properties can be accessed by using the '.' (dot) operator.

studentObj.toString();

Objects in JavaScript makes it easier to reuse JavaScript code. As a lot of interface code is written in JavaScript, using an object oriented programming style would be advantages in the long-run.

On a side note; I discovered the proper way to check whether the a variable is null in JavaScript.
if(!someVariable) instead of if(someVariable!=null)

No comments: