Writing a JavaScript Class
Writing classes in JavaScript doesn’t give full functionality of an object oriented language, but it at least gives data hiding and encapsulation which are very useful specially when JavaScript is not a strongly typed language. It is very useful in cases when you need to handle multiple objects, instead of having arrays for all kinds of variables and then managing those arrays in methods you can just write a class to handle one object and then make many instances of that class. This also gives the namespace resolution to the variables so that you can avoid using global variables and still use variables across procedures.
Definition of a JavaScript class – Definition of a class in JavaScript is done by just defining a no-parameter constructor. you can have constructors taking parameters but one constructor which doesn’t take any parameter is mandatory. The name of the class is the name of the constructor.
Instance Variables – To define instance variables of the class you have to initialize variables in the no-parameter constructor. In JavaScript the structures are defined by defining a variable and then defining other variables inside its namespace e.g.
var x; x.a = null; x.b = null;
defines a structure x with two variables a and b. In defining instance variables of a class we use the ‘this’ structure to define variables. e.g.
function Point()
{
this.x = null;
this.y = null;
}
One thing has to be kept in mind while using these instance variables in the member functions , that you have to use fully qualified name of the variable.
Member functions – To define member functions of the class you have to define functions in the same file and then store their pointers in the ‘this’ structure in the constructor. e.g.
function Point()
{
this.x;
this.y;
this.setX = setX;
this.setY = setY;
}
function Point(x,y)
{
this.x = x;
this.y = y;
}
function setX(x)
{
this.x = x;
}
function setY(y)
{
this.y = y;
}
Here also you have to keep in mind that to call a member function from another member function you have to use fully-qualified name.
Creating Instances – To create an instance of a class you have to use the following syntax
var myPoint = new Point(); or var myPoint = new Point(30,40);
If you found this post useful you may also want to check these out:
