Wiki Home

Simulating Classes In Java Script


Namespace: SoftwareEng
With thanks to Kurt Cagle of XML Fund. Kurt used to be the DHTML Pro for Dev X, so he got to know Java Script pretty well.
You use the function() keyword:

 
function Car(make,model,color,numDoors,transmission){
    this.make=make;
    this.model=model;
    this.color=color;
    if (numDoors==null){
        this.numDoors=4;
        }
    else {
        this.numDoors=numDoors;
        }
    if (transmission==null){
        this.transmission="Manual";
        }
    else {
        this.transmission=transmission;
        }
    this.action=carRun;
    }
 
function carRun(state){
    if (state=="Stop"){
        alert("Eeeeee...");
        }
    if (state=="Drive"){
        alert("Putt-putt-putt");
        }
    if (state=="Reverse"){
        alert("Ttup-ttup-ttup");
        }
    }

You can then create a new instance of this, using the name of the class as the constructor:

var car=new Car("Saturn","XJ4i","Silver");

You would then call the properties or methods just as you would for an intrinsic class:

alert(car.transmission + " " + car.make + " " + car.model);

will launch an alert box with the word "Manual Saturn" in it, while

car.action("Drive")

will launch a dialog box with "Putt-putt-putt" in it.

It's also possible to create limited inheritance with Javascript with the prototype method. This can let you define extended classes within a limited scope:

For example,
function CaliforniaCar(make,model,color,numDoors,transmission,sunroof){    
   var cr=new Car(make,model,color,numDoors,transmission);
   this.make=cr.make;
   this.model=cr.model; 
   this.color=cr.color;
   this.numDoors=cr.numDoors;
   this.transmission=cr.transmission;
   }
CaliforniaCar.prototype.sunroof=true;
 
var myNewCar=new CaliforniaCar();
if (myNewCar.sunroof){
    alert("NewCar:In Washington, it leaks!");
    }
else {
    alert("NewCar:Not having a sunroof in Washington is a good idea.");
    }
 
var myOldCar=new Car();
if (myOldCar.sunroof){
    alert("OldCar:In Washington, it leaks!");
    }
else {
    alert("OldCar:Not having a sunroof in Washington is a good idea.");
    }


Unfortunately, Javascript doesn't have a super keyword, so you have to to do aggregation to handle inheritance.
Here is a Java Script Sandbox that uses the eval() function and starts with simple object.
Category Web Tools Category Development Tools Category Web Development Category Code Samples
( Topic last updated: 2004.01.12 09:42:14 PM )