Objects are widely used in 'object-oriented' programming languages such as Java and C++ and they are an advanced topic in their own right. They are available in Java in two forms, as built-in objects and as user-defined objects. The main built-in objects available in browser-based versions of JavaScript are the Math object, the String object, the Date object and the Image object. Functions such as square root and sin are available in JavaScript through the Math object, for example:
Math.floor(Math.sqrt(x)) - this computes the integer part of a square root.
astr.charAt(5) - locates the 6th character (starting at zero) in string astr
today.getDate() - returns the day of the month
Objects have properties and methods. A property is a value stored in the object which can be accessed for some programming purpose. The dot (.) operator is used to access both object properties and methods. The String object has just one property, length, so one can write a loop which processes each character in a string based on, for example, string.length. The Math object has 6 properties including e (Math.E) and PI (Math.PI). Note that the case is important. The Date object has no properties.
Object methods are processes which are built in to the object when it is defined - encapsulation is the technical term, derived from the theory of object-oriented programming techniques. Methods which work on the contents of string objects are:
Methods are also available to change the appearance of strings from within JavaScript code:
big(), blink(), bold(), fixed(), fontcolor(c), fontsize(s), italics(), small(), strike(), sub(), sup().
The Math object properties are: E, LN10, LN2, PI, SQRT1_2 and SQRT2.
The Math object methods are:abs(n), acos(n), asin(n), atan(n), ceil(n), cos(n), exp(n), floor(n), log(n), max(n1, n2), min(n1, n2), pow(n1, n2), random(n), sin(ang), sqrt(n), tan(ang).
Here is an example which uses some Maths functions:
This is the code for the function:
function primes(){
var astr='0 1 ';document.primesform.primesout.value=astr;
var prime;
if ((document.primesform.primenums.value>0) &&
(document.primesform.primenums.value<=110)){
for (i=2;i<document.primesform.primenums.value;i++){
prime=true;
for (j=2;j <= Math.floor(Math.sqrt(i));++j){
if (i % j == 0) {prime=false;}}
if (prime==true) {astr+=i+' '};
document.primesform.primesout.value=astr;}}
else {document.primesform.primesout.value='number out of range, try again';}}
The function uses two functions of the Math object, floor() and sqrt().
String and Math objects do not need to be created with new. Strings gain their properties and methods from their normal definition (eg var astr='hello') while Math objects are always available - effectively as numbers. A date is created in one of three ways:
The Date object methods are:
The Date object methods can be used, along with some extra bits of JavaScript, to generate an on-screen digital clock:
The clock has three functions which together set an output area to a text string made up of the different components of the time and update it every second. The time is taken from the system clock of the host computer. The time between updates could be changed to more than one second or reduced, using milliseconds, to less. Here is the code:
var TimerID=null;
var TimerRunning=false;
function StopClock(){
if (TimerRunning)
clearTimeout(timerID);
TimerRunning=false;
}
function showtime(){
var now=new Date();
var hours=now.getHours();
var minutes=now.getMinutes();
var seconds=now.getSeconds()
var timeValue=""+((hours>12) ? hours -12 :hours)
timeValue+=((minutes<10) ? ":0" : ":") + minutes
timeValue+=((seconds<10) ? ":0" : ":") + seconds
timeValue+=(hours >=12) ? " P.M." : " A.M."
document.clockform.clock.value=timeValue;
timerID=setTimeout("showtime()",1000);
TimerRunning=true;
}
function StartClock(){
StopClock();
showtime();
}
The Form for the clock is very simple:
<FORM NAME="clockform"> <INPUT TYPE="text" NAME="clock" WIDTH=10 MAXLENGTH=10> </FORM>
The clock is started by adding an event handler to the <BODY> tag which calls the function and sets the clock running:
<BODY onLoad="StartClock()">
The functions include some extra JavaScript which can be useful in other ways:
timerID=setTimeout("showtime()",1000);
The setTimeout function provides a time interval in milliseconds and the name of a function which is called each time the interval elapses. The clearTimeout(timerID) function resets the Timeout interval.
An Image object provides ten properties and one method for manipulating images through JavaScript. One effect that this allows is animation of a sequence of images with a time interval which can be set to suit the images. One key property of the IMAGE object is src which is the URL of the image file, and complete which indicates when the browser has completed the loading of the image file.
You could use this technique for a range of animation techniques with greater degree of control than one has with, for example, animated GIFs. The slow speed of web page downloads means that images must either be very small or animations must contain very few frames. Here is the code:
var wait_images=new Array(3);
var wait_loop=0;
for (wait_loop=0; wait_loop<=2; wait_loop++)
{wait_images[wait_loop]=new Image;
wait_images[wait_loop].src="art"+wait_loop+".gif";}
var wait_img=0; var wait_id=0;
function wait_start(){
wait_img=++wait_img%3;
top.document.images.icon.src=wait_images[wait_img].src;
wait_id=setTimeout("wait_start();",1000);
}
function wait_stop()
{clearTimeout(wait_id);
top.document.images.icon.src='art0.jpg';
}
There are six lines of code here which are outside a function and run as they are read by the browser. There are two functions, the first of which loads an image and sets a timeout value which waits for the time shown and then replaces it with the next in the sequence. The second function is called by the Stop button on the Form, removes the timeout value and resets the image to a single image.
For four images the array size is set to 3: 0, 1, 2 & 3 makes 4 cells for images. The in-line code sets up the array before the form is reached. The Animate button calls wait_start which sets the current image to that stored in an array cell indexed by wait_img. The value of wait_img is kept within the range 0-3 by taking the remainder after dividing by 4.
Here is the form:
<IMG id="icon" src="art0.jpg"> <FORM NAME="anim1"> <INPUT TYPE="BUTTON" VALUE="Animate" OnClick="wait_start()"> <INPUT TYPE="BUTTON" VALUE="Stop" OnClick="wait_stop()"> </FORM>Return to Javascript Menu