<!-- Part of javalessons.com (c)2007 SEMM(NL) All rights reserved Author:P.Hamaker For educational purposes only.-->
<html><head>
<style type="text/css">
body{
font-family: sans-serif; font-size: large; margin-left: 20; margin-top: 30
}
.err{
visibility: hidden;font-style: italic;font-weight: bold; color: red;
 }</style>
<script type="text/javascript">
var ct1 = null, ct2 = null ;

function City( nm, nres, cc  )
{
 this.name = nm ;
 this.nr_residents = nres ;
 this.prev_nr_res = 0 ;
 this.country_cd = cc ;

 this.add = function( n )
 {
  this.prev_nr_res = this.nr_residents ;
  this.nr_residents += n ;
 }
}

function doit()
{
 var ta = document.getElementById('ta1') ;
 ta.value = '' ;
 if ( ct1 == null )
 {
   ct1 = new City( 'Amsterdam', 744011, 'NL'  ) ;
   ta.value = 'City instance ct1 created\n' ;
 }
 if ( ct2 == null )
 {
   ct2 = new City( 'Haule', 1221, 'NL'  ) ;
   ta.value += 'City instance ct2 created\n' ;
   var b = document.getElementById('bt2') ;
   b.disabled = false ;
 }
 ta.value +=
  ct1.name + ', ' + ct1.nr_residents + ', ' + ct1.country_cd + '\n';
 ta.value +=
  ct2.name + ', ' + ct2.nr_residents + ', ' + ct2.country_cd + '\n';
 
 with ( ct1 )
 {
   ta.value += name + ' has ' + nr_residents + ' residents\n';
 }
}
function addum()
{
 var ta = document.getElementById('ta1') ;
 ta.value = '' ;
 var inp = parseInt( document.getElementById('tx1').value ) ;
 if ( isNaN( inp ) )
 {
  document.getElementById('tx1err').style.visibility='visible';
  document.getElementById('tx1').focus();
  return;
 }
 if ( ct2 != null )
 {
   ct2.add( inp ) ;
   ta.value += ct2.name + ' now has ' + ct2.nr_residents + ' residents\n';
   ta.value += ct2.name + ' had ' + ct2.prev_nr_res + '\n';
 }
}
</script>
</head>
<body>
JavaScript Lesson Custom Objects<p>
<form>
<table><tr valign="top"><td>
<input id="tx1" type="text" maxlength="7" size="9" style="text-align: right"
         onkeydown="tx1err.style.visibility='hidden'">
<span id="tx1err" class="err">Wrong input</span>
<br>
<input id="bt1" type="button" value="Do it" onclick="doit()">
<input id="bt2" type="button" value="Add" onclick="addum()" disabled>
<input type="reset" value="Reset" onclick="ct1=ct2=null;bt2.disabled=true;">
</td><td>
<textarea id="ta1" rows="7" cols="35" readonly="readonly"></textarea>
</td></tr></table>
</form>
<p><a href="http://javalessons.com" target="_top"><tt>JavaLessons.com</tt></a>
</body></html>