4/29/08

How to create a class in JavaScript

It turns out that JavaScript does not really support classes - weird... But there is a way to create them. Since everything is a function, create functions that that you need. Think of them as your class private methods. Start by creating a function that represents the constructor. In the constructor create methods and properties that connect to the private functions and variables using the assignment operator.

For example:


//privates
var firstName;
var lastName;
var isAdmin;
var hours = 0;


//constructor
function Worker(var workingHoursAWeek)
{
//passes personsAge to private var hours
hours = workingHoursAWeek;
//creates properties
this.FirstName = firstName;
this.LastName = lastName;
this.Hours= hours;
this.IsAdmin = isAdmin;


//create a method
this.IsBusy = isBusy;
}


//private function
function isBusy()
{
return (hours > 40) ? true : false;

}
Store the code in a separate .js file.
To use the class, include it in your .htm file
by passing it to scr



<script type="text/javascript" src="Worker.js"></script>

Now you can create an object and use it's properties and methods:

Worker denis = new Worker(40);
denis.Hours += 5;
if (denis.IsBusy) alert("help!");

_________________________________________________________

It is always great to see a working sample. Here I am going to use the exercise 11.16 from Deitel's "Internet & World Wide Web - How to program", which strangely does not show you how to create a class in JavaScript.
_________________________________________________________



Step 1. create a new JavaScript file "AirplaneReservationSystem.js" with the following code:



var SIZE;
var FIRST_CLASS_LIMIT;
var seats;

function AirplaneReservationSystem(size, firstClassLimit)
{
SIZE = size;
FIRST_CLASS_LIMIT = firstClassLimit;
seats = new Array(SIZE);
for(var i = 0; i < seats.length; i++)
seats[i] = "empty";
this.ReserveEconomy = reserveEconomy;
this.ReserveFirstClass = reserveFirstClass;
this.Seats = seats;
this.IsFull = IsFull;
}

function reserveEconomy()
{
var seat = -1;
for( var i = FIRST_CLASS_LIMIT; i <= SIZE; i++)
{
if(seats[i] == "empty")//if there are seats available
{
seats[i] = "full";
seat = i + 1;
i = SIZE;
}
}
return seat;
}

function reserveFirstClass()
{
var seat = -1;
for( var i = 0; i < FIRST_CLASS_LIMIT; i++)
{
if(seats[i] == "empty")
{
seats[i] = "full";
seat = i + 1;
i = FIRST_CLASS_LIMIT;
}
}
return seat;
}


function IsFull()
{
for(var i = 0; i <>(seats[i] == "empty")
return false; //found a seat
return true; //plane's full
}

Step 2.
create and .htm file where you can use the above class. Here is the code for it:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Excercise 11.16</title>
<script type="text/javascript" src="AirplaneReservationSystem.js"></script>
<script type="text/javascript">

    var SIZE = 9;
var FIRST_CLASS_LIMIT = 5;
var airplane = new AirplaneReservationSystem(SIZE, FIRST_CLASS_LIMIT);
var seat;
function ReserveSeat()
{
if(airplane.IsFull())
alert("Airplane is full");
else //reserve a seat
{
if(form.ticket[0].checked)//First Class
{
window.status = "Reserving First Class ticket...";
seat = airplane.ReserveFirstClass();
if(seat != -1)
window.status = "Reserved a seat number " + seat + " in FirstClass.";
else //first class is full
{
if(confirm("Can we try to place you in Economy?")==true)
{
seat = airplane.ReserveEconomy();
window.status = "Reserved a seat number " + seat + " in Economy.";
}
else
alert("Next plane leaves in 3 hours");
}
}
else if(form.ticket[1].checked)//Economy
{
window.status = "Reserving Economy ticket...";
seat = airplane.ReserveEconomy();
if(seat != -1)
window.status = "Reserved a seat number " + seat + " in Economy.";
else //economy is full
{
if(confirm("Can we try to place you in First Class?") == true)
{
seat = airplane.ReserveFirstClass();
window.status = "Reserved a seat number " + seat + " in FirstClass.";
}
else
alert("Next plane leaves in 3 hours");
}
}
else
alert("Select ticket type before reserving the seat");
}
}

</script>
</head>
<body>
<form name="form" action="">
<h1>Airline Reservation System</h1>
<br />
<br />
<p>
<input type="radio" name="ticket" value="FirstClass"/>
<label>First Class</label>
<br />
<input type="radio" name="ticket" value="Economy"/>
<label>Economy</label>
<br />
<br />
<input type="button" value="Reserve Seat" onclick="ReserveSeat()" />
</p>
<br />
<br />
<label>Result: </label>
<input name="Result" type="text" />
</form>
</body>
</html>

No comments:

Post a Comment