Objects, part one
Notes from April 20, 2005 class
Roll your own HTML via JavaScript
In class, we created a script whose only purpose is to output into the browser window an html framework into which you can put a JavaScript. That way, whenever you need to write a javascript, you can just run this script in a browser and copy what shows up on the screen into a blank page in Notepad or the text editor of your choice. The output, in a browser, contains the following (though with some space between the lines):
<html>
<head>
<title>Make HTML Page with JavaScript</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
/ /-->
</script>
</body>
</html>A working copy of this script is available. Notice in the JavaScript code, to get JavaScript to print out what looks like HTML code, you have to tell it to print the ASCII code that corresponds to a < (less than) and to a > (greater than) :
< < > > Properties and Methods
An object is really just a "thing" that has properties and methods. For a real-world example, most of us have an object called a "car".
Among the properties of a "car" object would be the color, number of doors, type of engine, manufacturer, model, and of course, the type of audio equipment.
Methods are, defined simply, the different ways in which an object is used. Among the methods for a "car" object might be such things as to commute, to run errands, to race, to sightsee, to cruise for dates, and so on.
Here's how you assign a variable to a new object you've just created, all in the same line of code:
var myVariable = new ObjectName(optional parameters);
The keyword "new" in front of the function name is what tells JavaScript to spawn a new instance of the object. So, for example:
var myDate = new Date();
will create a new variable called myDate. That myDate variable will be a JavaScript Date object, which is a native object that's already part of JavaScript.
Native objects are objects that have already been defined within the JavaScript core itself, so they're also known as JavaScript core objects. Each native object comes with a variety of properties and methods that have been already written into the core JavaScript code, that you can use when you need to manipulate or calculate. For example, in the code we just wrote:
var myDate = new Date();
Since I didn't specify otherwise within the parentheses, myDate will be a Date object containing the date and time it was created (the moment when the JavaScript was run in the user's browser).
I can create a new Date object and set the variable to whatever I want it to be, by passing that information as a parameter:
var theMilleniumStart = new Date("1 Jan 2001");
Methods
Remember, a method is a different way in which an object is used. Suppose I want to tell the user how many hours from Greenwich Mean Time they are. I could look in Appendix B of our textbook and find a helpful method for the Date object, getTimezoneOffset():
var myDate = new Date();
var UTCdifference= myDate.getTimezoneOffset();
// note: to call a method for an object you put the object name, a dot, and the method
alert ("The difference between your time and UTC is " + UTCdifference + " minutes, or " + UTCdifference/60 + " hours.");Check Appendix B of the textbook (from page 900 forward) for a list of JavaScript core objects and the properties and methods for each of them.
Later on in the class, we can use the sort() method to change the order of information in an array:
myArray.sort();
This code:
var myDate = new Date();
document.write("You visited this page at " + myDate);is just dumping the value of the Date object onto the page. Because we've not told it otherwise, JavaScript is going to include everything it knows about the date. It will display in the browser like this:
You visited this page at Wed Apr 20 2005 12:26:14 GMT-0700
You might be cluttering the screen, and the user's brain, with more information than they needed. So, we can use our handy Appendix B to find some methods for the date object we're using, that'll let us extract and display only the information you wanted to display.
var myDate = new Date();
document.write("You visited this page during the year "+ myDate.getFullYear()+"<br />");
document.write("You arrived at "+ myDate.getHours() + ":" + myDate.getMinutes() );
//notice we had to add in the colon between the hours and minutes
//notice, two sets of closing parenthesesHere's a script that includes all the date object methods used in the above examples.
Properties
To access the properties of an object, it works pretty much like accessing its method: the object name, a dot, and the object property. For example, among the JavaScript objects we've already used without identifying it as an object was the Array. Well, it turns out that among the properties of an array object is its length. So, instead of having to physically count every single item in an array, you can just use the .length property for that particular array to get that information.
var myArray = new Array("blah1", "blah2", "blah3");
var loopThis = myArray.length; //solves that nasty "loop till done" problemMost JavaScript objects just have a handful of properties, but many have a lot of available methods by which you can use the object.
Functions can be objects, too
A function object is a block of JavaScript code that is compiled to perform a specific task. JavaScript has lots of built-in functions, some of which we've already seen:
parseInt();
parseFloat();In class, we created our own JavaScript object, a function called "car", using a function constructor. (The script is available here.) This is a pretty silly idea for a function, but it's good practice in thinking about how we use an object and its properties.
<html>
<head><title>The Car Function</title>
<script language="JavaScript" type="text/javascript">
<!--
/*we're putting this information into the <head></head> of the document, so it'll load first*//*begin the "constructor function", which lets you build the object using the same syntax as in a regular function*/
function car(seats,engine,theradio)
{
this.seats=seats;
this.engine=engine;
this.theradio=theradio;
}//that's it for the constructor function
/*now we create a couple instances of the function, sending parameters to use as property values*/
var work_car = new car("cloth", "V-6", "Tape Deck");
var fun_car = new car("leather", "V-8", "CD/MP3 Player");/*now we'll assign a couple properties of these new instance of the function to independent variables*/
var engine_type=work_car.engine;
var seat_type=fun_car.seats;
var radio_type=fun_car.theradio;//-->
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
/*the document.write() commands are used in the <body></body> section so they'll display in the browser*/document.write("My work car has " + work_car.seats + " seats.<br />")
document.write("I want a car with "+ seat_type + " seats.<br />");
document.write("It also needs a " + engine_type + " engine.<br />");
document.write("Oh, yeah, and I'd like a " + radio_type + ", also.<br />");//-->
</script>
</body>
</html>
We can save some time by creating a new instance of the object, sending the values of the properties of other object instances as parameters. Often within JavaScript, you can use object properties like variables, which can cut down on the amount of code you need to write.
<html>
<head><title>The Car Function</title>
<script language="JavaScript" type="text/javascript">
<!--
//constructor functionfunction car(seats,engine,theradio)
{
this.seats=seats;
this.engine=engine;
this.theradio=theradio;
}//end constructor function
/*now we create a couple instances of the function, sending parameters to use as property values*/
var work_car = new car("cloth", "V-6", "Tape Deck");
var fun_car = new car("leather", "V-8", "CD/MP3 Player");/*and one new instance that sends the values of the properties of other object instances as parameters*/
var custom_car = new car(fun_car.seats,work_car.engine,fun_car.theradio);//-->
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!--
/*the properties of the new instance of the object, custom_car, are used like variables in the document.write() statements*/document.write("My work car has " + work_car.seats + " seats.<br />")
document.write("I want a car with "+ custom_car.seats + " seats.<br />");
document.write("It also needs a " + custom_car.engine + " engine.<br />");
document.write("Oh, yeah, and I'd like a " + custom_car.theradio + ", also.<br />");//-->
</script>
</body>
</html>