Classes

Javascript class definitions are done differently to VFP class definitions.

To define a class we create a function with the same name as the class name. This function will be the equivalent of the init function in VFP and the class will be based on the VFP custom baseclass.

So we can have

function circle(){

}

var x = new circle();

This will create an object of class circle which is empty.

We will now change this to add properties

function circle(radius){

   this.radius=radius;

}

var x = new circle(10);

We have now added a property called radius to the class. Also we are initializing it at the time of creation by sending a parameter to the class 'init' event.

We will add a function to this class.

function circle(radius){

   this.radius=radius;

   this.area=function(){

      return Math.PI * this.radius * this.radius;

   }

}

var x = new circle(10);

alert(x.area());

We have added a function to the class called area. (Math is a global variable available in javascript. It has a property called PI). Methods will be functions without the return statement.

Prototyping

To add properties or methods to existing classes we use the prototype property

circle.prototype.circumference=function(){

   return 2*Math.PI * this.radius; }

alert(x.circumference());

Here the circle class was already defined. We have now added another function to the circle class.

In VFP it is not possible to change class definition if an object based on it is created. In javascript, we have done just that.

The variable x was created first, the circumference function was added to the class later, but the x variable is updated to accept the circumference function.

We can also add properties to classes after they have been created with the prototype property.

circle.prototype.name='MyCircle';

alert(x.name);

We can add properties and methods to javascript base classes too with the prototype property. This is not the same as the VFP subclassing as we are directly altering the baseclass.

Leave a Reply

Your email address will not be published. Required fields are marked *