Home / Javascript / Archive by category 'Object oriented Javascript'

Object oriented Javascript

Create and display custom objects using JavaScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Create and Display Object Types</title>
</head>
<script language="JavaScript">
 
// ************************************************************************
// CREATE AN AUTOMOBILE USING A CONSTRUCTOR
// ************************************************************************
function Automobile(manufacturer, model, series)
{
 
 
    // ************************************************************************
	// DEFINE AUTOMOBILE ATTRIBUTES
	// ************************************************************************
    this.manufacturer= manufacturer;
    this.model = model;
    this.series = series;
 
}
 
 // ************************************************************************
// DEFINE BEHAVIOR TO RETURN AUTOMOBILES
// ************************************************************************
function getAutomobileInfo()
{
 
 // ************************************************************************
// CREATE VARIOUS AUTOMOBILES OBJECTS
// ************************************************************************
 
	astonMartin1 = new Automobile("Aston Martin", "DB", "DB9 Sports Pack");
	astonMartin2 = new Automobile("Aston Martin", "DB", "DB RS9");
	astonMartin3= new Automobile("Aston Martin", "Vanquish", "V12 S");
	astonMartin4 = new Automobile("Aston Martin", "Vanquish", "Roadster");
 
	bmw1 = new Automobile("BMW","M Series","Coupe");
	bmw2 = new Automobile("BMW","M Series","Convertible");
	bmw3 = new Automobile("BMW","Z Series","Roadster");
	bmw4 = new Automobile("BMW","Z Series","Z3");
 
	jaguar1 = new Automobile("Jaguar","X-Type","Sedan");
	jaguar2 = new Automobile("Jaguar","X-Type","Wagon");
	jaguar3 = new Automobile("Jaguar","XK","Roadster");
	jaguar4 = new Automobile("Jaguar","XK","RS");
 
	mercedesBenz1 = new Automobile("Mercedes Benz","SLR","350");
	mercedesBenz2 = new Automobile("Mercedes Benz","SLR","55");
	mercedesBenz3 = new Automobile("Mercedes Benz","SL-Class","SL600 Roadster");
	mercedesBenz4 = new Automobile("Mercedes Benz","SL-Class","SL65 AMG Roadster");
 
	porsche1 = new Automobile("Porsche","911","Turbo");
	porsche2 = new Automobile("Porsche","911","GT#");
	porsche3 = new Automobile("Porsche","Boxster","2.5");
	porsche4 = new Automobile("Porsche","Boxster","S");
 
// ************************************************************************
// PRINT AUTOMOBILE OBJECTS ONTO WEB PAGE
// ************************************************************************
 
    document.write("Manufacturer:" + astonMartin1.manufacturer + "<br>" +
    			   "Model :" + astonMartin1.model + "<br>" +
    			   "Series :" + astonMartin1.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin2.manufacturer + "<br>" +
    			   "Model :" + astonMartin2.model + "<br>" +
    			   "Series :" + astonMartin2.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin3.manufacturer + "<br>" +
    			   "Model :" + astonMartin3.model + "<br>" +
    			   "Series :" + astonMartin3.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin4.manufacturer + "<br>" +
    			   "Model :" + astonMartin4.model + "<br>" +
    			   "Series :" + astonMartin4.series + "<br><br>");
}
 
 
 
 
</script>
</head>
 
<body bgcolor = "#FFFFFF">
 
<!-- INSERT JAVASCRIPT TO CALL BEHAVIOR-->
<script language="JavaScript">
 
	getAutomobileInfo();
 
</script>
 
</body>
</html>

Create a Monthly Auto Loan Payment Calculator in Javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Loan Calculator</title>
</head>
 
<script language="JavaScript">
			function calculateLoan()
			{
				nMon = document.form1.txtNumerOfMonths.value;
				iRate = document.form1.txtInterestRate.value;
				aFinanced = document.form1.txtAmountFinanced.value;
				mPayment = (iRate * aFinanced)/ nMon;
 
				alert('Your monthly payment would be $ ' + Math.round( mPayment ) );
 
			}
 
	</script>
 
 
</head>
 
<form name="form1">
<body bgcolor="#FFFFFF" LANGUAGE=JavaScript >
 
 
<h2 align="center" class="LabelLarge">Monthly Auto Loan Payment Calculator</h2>
  <table align="center" border="0" cellspacing="8" cellpadding="8">
    <tr>
      <td width="98" align="right" class="boldText"> Number of Months:</td>
      <td width="159">
 
       	<!-- Add a text box to capture Number of Months input-->
      	<input name="txtNumerOfMonths" type="text" size="6" maxlength="6" />
 
      </td>
    </tr>
    <tr>
      <td align="right" class="boldText">Interest Rate:</td>
      <td> <span class="text">
        <input name="txtInterestRate" type="text" size="6" maxlength="6" />
        </span></td>
    </tr>
    <tr>
      <td align="right" class="boldText"> Amount Financed:</td>
      <td>
 
      	<!-- Add a text box to capture Amount Financed input-->
      	<input name="txtAmountFinanced" type="text" size="6" maxlength="6" />
 
      	</td>
    </tr>
    <tr>
      <td colspan="2" valign="top"><div align="center">
 
       <!-- Add a button to execute JavaScript function-->
        <input name="button" type="button" value="Calculate" onClick="calculateLoan()"/>
 
        <input name="reset" type="reset" />
        </div></td>
    </tr>
  </table>
</form>
</body>
</html>

Illustrate how to manipulate JavaScript variables for web pages

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Creating JavaScript variables for web pages 1</title>
</head>
 
<script language="JavaScript">
 
 // ************************************************************************
// DEFINE BEHAVIOR TO ACCESS ATTRIBUTES
// ************************************************************************
function getFullName()
{
  var firstName, lastName, fullName;
 
  firstName = document.form1.txtFirstName.value;
  lastName  = document.form1.txtLastName.value;
 
  fullName  = firstName + " " + lastName;
 
 // ************************************************************************
// DISPLAY ATTRIBUTE ONTO WEB PAGE
// ************************************************************************
  document.form1.txtFullName.value = fullName;
 
 
}
 
</script>
 
</head>
<body>
 
<h2 font face="Arial" color="#FF0000">
  Credit Application</h2>
 
<font face="Arial" size="3">
<form name="form1">
  <table border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="100">First Name:</td>
 
      <!-- Add text box for first name -->
      <td><input type="text" name="txtFirstName" size="14"></td>
 
    </tr>
    <tr>
      <td width="100">Last Name:</td>
 
      <!-- Add text box for last name -->
      <td><input type="text" name="txtLastName" size="14"></td>
 
    </tr>
    <tr>
      <td width="100">Full Name:</td>
 
       <!-- Add text box to display full name -->
      <td><input type="text" name="txtFullName" size="30"></td>
 
    </tr>
    <tr>
      <td width="100"><br><br></td>
      <td>
 
        <!-- Add button to call JavaScript function -->
        <input type="button" value="Show Full Name" onClick="getFullName()">
 
      </td>
    </tr>
  </table>
</form>
</font>
 
</body>
</html>

Example of Encapsulation using JavaScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>JavaScript - Encapsulation Exercise</title> 
</head> 
 
<body> 
<p> 
  <script language="JavaScript" type="text/JavaScript"> 
 
   // ************************************************************************
   // CREATE AN AUTOMOBILE USING A CONSTRUCTOR
   // ************************************************************************
	function Automobile(speed)
	{
 
   // ************************************************************************
   // PUBLIC PROPERTY -- ANYONE MAY READ/WRITE
   // ************************************************************************
   		this.model = "Standard";
 
   // ************************************************************************
   // PRIVATE VARIABLE AND FUNCTION
   // ONLY PRIVELEGED METHODS MAY VIEW/EDIT/INVOKE
   // ***********************************************************************
		var drivingSpeed = speed;
		var milePerGallonValue1 = 0;
		var milePerGallonValue2 = 0;
 
 
   // ************************************************************************
   // PRIVILEGED METHODS
   // MAY BE INVOKED PUBLICLY AND MAY ACCESS PRIVATE ITEMS
   // MAY NOT BE CHANGED; MAY BE REPLACED WITH PUBLIC FLAVORS
   // ************************************************************************
 
		this.setMilePerGallonEquation = function(param1, param2)
		{
			milePerGallonValue1 = param1;
			milePerGallonValue2 = param2;
		}
 
		this.getMilePerGallonEquation = function()
		{
			return milePerGallonValue1 * milePerGallonValue2;
		}
 
		this.getBaseMilesPerGallon = function()
		{
		   return Math.round(  drivingSpeed / this.getMilePerGallonEquation() );
		}
 
		this.setBaseSpeed = function(newSpeed)
		{
		   drivingSpeed = newSpeed;
		}
 
		this.getBaseSpeed = function()
		{
		   return drivingSpeed;
		}
 
 
	}
 
 
	// ************************************************************************
	// PROTOTYOPE PROERTIES -- ANYONE MAY READ/WRITE (but may be overridden)
	// ************************************************************************
	Automobile.prototype.tankSize = 13;
 
 
	// ************************************************************************
	// STATIC PROPERTIES -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.opinion = "";
 
 
	// ************************************************************************
	// PUBLIC METHODS -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.prototype.setIdealSpeed = function(ideal)
	{
		this.idealSpeed = ideal;
	}
 
	Automobile.prototype.getIdealSpeed = function()
	{
		return this.idealSpeed;
	}
 
 
	Mercedes.prototype = new Automobile();
	function Mercedes(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
	Porsche.prototype = new Automobile();
	function Porsche(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
 
	 function performTest()
	 {
		autoMobileObject = new Array(3)
		autoMobileObject[0]  = new Automobile(50);
		autoMobileObject[1] = new Mercedes( autoMobileObject[0] );
		autoMobileObject[2] = new Porsche( autoMobileObject[0] );
 
		autoMobileObject[0].setMilePerGallonEquation(.015, 100);
		autoMobileObject[1].setMilePerGallonEquation(.03, 100);
		autoMobileObject[2].setMilePerGallonEquation(.02, 100);
 
 
		alert("At " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A BASIC AUTOMOBILE
	// ******************************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
 
		alert("At " + autoMobileObject[1].getBaseSpeed() + " mph. the " + autoMobileObject[1].model +  " version of my Mercedes with a " + autoMobileObject[1].tankSize  + " gallon tank will get " + autoMobileObject[1].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ********************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A MERCEDES
	// *********************************************************************************************************
		if( autoMobileObject[1].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
		alert("At " + autoMobileObject[2].getBaseSpeed() + " mph. the " + autoMobileObject[2].model +  " version of my Porsche with a " + autoMobileObject[2].tankSize  + " gallon tank will get " + autoMobileObject[2].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A PORSCHE
	// ******************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	// ************************************************************************************************************
	// CHANGE THE IDEAL SPEED USING PUBLIC PROPERTIES AND PRIVILEGED METHODS
	// ************************************************************************************************************
		autoMobileObject[0].setIdealSpeed(65);
 
		alert("For best performance the ideal speed is around " +  autoMobileObject[0].getIdealSpeed() + " mph." );
 
		autoMobileObject[0].model = "Luxury";
		autoMobileObject[0].tankSize = 20;
		autoMobileObject[0].setBaseSpeed(70);
 
		alert("However, at " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	 }
 
</script> 
 
</p> 
<p align="center"><font size="+3" face="Arial, Helvetica, sans-serif">Encapsulation
  Example</font></p> 
<p align="center">&nbsp;</p> 
<form name="form1" method="post" action=""> 
  <div align="center"> 
 
    <!-- Add button to call JavaScript function --> 
    <input type="button" name="peformTest" value="Perform Test" onclick="javascript:performTest()"> 
 
  </div> 
</form> 
</body> 
</html>

Example to illustrate Polymorphism using JavaScript

To illustrate Polymorphism using JavaScript we define a base object called Automobile with attributes and behaviors. Then we create sub object called Mercedes and Porshce to share the Automobiles attributes and behaviors.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>JavaScript - Polymorphism Example</title> 
</head> 
 
<body> 
<p> 
  <script language="JavaScript" type="text/JavaScript"> 
 
	function Automobile(speed)
	{
   // ************************************************************************
   // PUBLIC PROPERTY -- ANYONE MAY READ/WRITE
   // ************************************************************************
   		this.model = "Standard";
 
   // ************************************************************************
   // PRIVATE VARIABLE AND FUNCTION
   // ONLY PRIVELEGED METHODS MAY VIEW/EDIT/INVOKE
   // ***********************************************************************
		var drivingSpeed = speed;
		var milePerGallonValue1 = 0;
		var milePerGallonValue2 = 0;
 
 
   // ************************************************************************
   // PRIVILEGED METHODS
   // MAY BE INVOKED PUBLICLY AND MAY ACCESS PRIVATE ITEMS
   // MAY NOT BE CHANGED; MAY BE REPLACED WITH PUBLIC FLAVORS
   // ************************************************************************
 
		this.setMilePerGallonEquation = function(param1, param2)
		{
			milePerGallonValue1 = param1;
			milePerGallonValue2 = param2;
		}
 
		this.getMilePerGallonEquation = function()
		{
			return milePerGallonValue1 * milePerGallonValue2;
		}
 
		this.getBaseMilesPerGallon = function()
		{
		   return Math.round(  drivingSpeed / this.getMilePerGallonEquation() );
		}
 
		this.setBaseSpeed = function(newSpeed)
		{
		   drivingSpeed = newSpeed;
		}
 
		this.getBaseSpeed = function()
		{
		   return drivingSpeed;
		}
 
 
	}
 
 
	// ************************************************************************
	// PROTOTYOPE PROERTIES -- ANYONE MAY READ/WRITE (but may be overridden)
	// ************************************************************************
	Automobile.prototype.tankSize = 13;
 
 
	// ************************************************************************
	// STATIC PROPERTIES -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.opinion = "";
 
 
	// ************************************************************************
	// PUBLIC METHODS -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.prototype.setIdealSpeed = function(ideal)
	{
		this.idealSpeed = ideal;
	}
 
	Automobile.prototype.getIdealSpeed = function()
	{
		return this.idealSpeed;
	}
 
 
	Mercedes.prototype = new Automobile();
	function Mercedes(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
	Porsche.prototype = new Automobile();
	function Porsche(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
 
	 function performTest()
	 {
		autoMobileObject = new Array(3)
		autoMobileObject[0]  = new Automobile(50);
		autoMobileObject[1] = new Mercedes( autoMobileObject[0] );
		autoMobileObject[2] = new Porsche( autoMobileObject[0] );
 
		autoMobileObject[0].setMilePerGallonEquation(.015, 100);
		autoMobileObject[1].setMilePerGallonEquation(.03, 100);
		autoMobileObject[2].setMilePerGallonEquation(.02, 100);
 
 
		alert("At " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A BASIC AUTOMOBILE
	// ******************************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
 
		alert("At " + autoMobileObject[1].getBaseSpeed() + " mph. the " + autoMobileObject[1].model +  " version of my Mercedes with a " + autoMobileObject[1].tankSize  + " gallon tank will get " + autoMobileObject[1].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ********************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A MERCEDES
	// *********************************************************************************************************
		if( autoMobileObject[1].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
		alert("At " + autoMobileObject[2].getBaseSpeed() + " mph. the " + autoMobileObject[2].model +  " version of my Porsche with a " + autoMobileObject[2].tankSize  + " gallon tank will get " + autoMobileObject[2].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A PORSCHE
	// ******************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	// ************************************************************************************************************
	// CHANGE THE IDEAL SPEED USING PUBLIC PROPERTIES AND PRIVILEGED METHODS
	// ************************************************************************************************************
		autoMobileObject[0].setIdealSpeed(65);
 
		alert("For best performance the ideal speed is around " +  autoMobileObject[0].getIdealSpeed() + " mph." );
 
		autoMobileObject[0].model = "Luxury";
		autoMobileObject[0].tankSize = 20;
		autoMobileObject[0].setBaseSpeed(70);
 
		alert("However, at " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	 }
 
</script> 
 
</p> 
<p align="center"><font size="+3" face="Arial, Helvetica, sans-serif">Polymorphism
  Example</font></p> 
<p align="center">&nbsp;</p> 
<form name="form1" method="post" action=""> 
  <div align="center"> 
 
    <!-- Add button to call JavaScript function --> 
    <input type="button" name="peformTest" value="Perform Test" onclick="javascript:performTest()"> 
 
  </div> 
</form> 
</body> 
</html>

Example to illustrate Inheritance using JavaScript

In the example we define a base object called Car, and Create sub object called ferrari that inherits attributes from Car.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Inheritance Example</title>
</head>
 
<body>
<p>
  <script language="JavaScript" type="text/JavaScript">
 
 
 // ************************************************************************
 //Define a Car object
 // ************************************************************************
 function Car()
 {
	 //Add attributes to the Car
	 this.mileage = 0;
	 this.category = "Vehicle";
 }
 
 
  // ************************************************************************
 // Define a ferrari object
 // ************************************************************************
 function ferrari()
 {
 	 //Add attributes to the ferrari
 	this.mileage = 100;
	this.weight = 400;
 }
 
 // ************************************************************************
 // Use the ferrari prototype to inherit from Car
  // ************************************************************************
 ferrari.prototype = new Car();
 
  //Use the ferrari prototype to inherit from Car
 ferrari.prototype.getMileage = function()
 {
    return this.mileage;
 }
 
 // ************************************************************************
  // Use the ferrari prototype to access Car attributes
  // ************************************************************************
 CashRegister.prototype.getCategory = function()
 {
    return this.category;
 }
 
 // ************************************************************************
 // Define a JavaScript function to drive the test
 // ************************************************************************
 function performTestonInheritance()
 {
 
	  // ************************************************************************
	  // Create an instance of myFerrari
	  // ************************************************************************
	  var myFerrari= new ferrari();
 
	 // ************************************************************************
	 // Access the redifined attribute of ferrari
	 // ************************************************************************
	 alert("The mileage is: " + myFerrari.getMileage() );
 
	 // ************************************************************************
	 // Access the base attribute of ferrari
	 // ************************************************************************
	 alert("The category is: " + myFerrari.getCategory() );
 
 }
 
</script>
 
 
</p>
Inheritance in Javascript  Example
<br/>
<form name="form1" method="post" action="">
  <div align="center">
 
    <!-- Add button to call JavaScript function -->
    <input type="button" name="peformTest" value="Perform Inheritance Test" onclick="javascript:performTestonInheritance()">
 
  </div>
</form>
</body>
</html>

Attaching an event in Javascript

All major browsers support the method addEventListener (), which is part of the W3C model. The following example shows how to attach an event a button so that it works in all browsers:

<script language="JavaScript"
type="text/JavaScript">
function eventHandler() {
window.alert("Event fired!");
}
window.onload = function() {
var button =
document.getElementById("eventButton");
if (button.addEventListener) {
button.addEventListener("click", eventHandler, false);
} else if (button.attachEvent) {
button.attachEvent("onclick", eventHandler);
}
};
</script>
<input type="button" id="eventButton"
value="Click me!" />

You can also delete the event handlers. Internet Explorer uses detachEvent (), while other browsers follow the W3C recommendations and appoint their functions removeEventListener ().


Extension of the Date class in Javascript

The prototype property can also be used to extend JavaScript classes. In the following code, ISLEAPYEAR function () is implemented. It determines if the return value of getFullYear () is a leap year. ISLEAPYEAR () becomes a method of the Date object and therefore has access to Date.getFullYear().

<script language="JavaScript" type="text/JavaScript">
function isLeapYear() {
var y = this.getFullYear();
return (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
}
Date.prototype.isLeapYear = isLeapYear;
var d = new Date();
window.alert(d.isLeapYear());
</script>

Inheritance with prototype in Javascript

<script language="JavaScript"
type="text/JavaScript">
function UniversalTranslator() {
this.copyright = "(C) 2010 JavaScript Examples";
}
function UniversalCounter() {
this.Count = count;
var numbers = {
"en": "one, two, three",
"fr": "un, deux, trois",
"de": "eins, zwei, drei"
};
function count(language) {
if (numbers[language]) {
window.alert(numbers[language] + " [" + this.copyright + "]");
} else {
window.alert("Unknown language");
}
}
}
UniversalCounter.prototype =
new UniversalTranslator();
var uc = new UniversalCounter();
uc.Count("de");
</script>

A simple class in Javascript

<script language="JavaScript"
type="text/JavaScript">
function UniversalClass() {
window.alert("Welcome to my class!");
}
var uc = new UniversalClass();
</script>