A Dictionaryobject behaves very much like a JavaScript array that has string index values similar to a Java hash table, although numeric index values are also acceptable in the Dictionar
Trang 1segment easier to find For example, you can define a comment block above each function and describe what the function is about, as in the following example
/* -calculate()
Performs a mortgage calculation based on parameters blah, blah, blah Called by blah blah blah.
-*/
function calculate(form) {
statements
}
const
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
The constkeyword initializes a constant Unlike a variable, whose data is sub-ject to change while a page loads, a constant’s value cannot be modified once it is assigned It is common practice in many programming languages to define constant identifiers with all uppercase letters, usually with underscore characters to delimit multiple words This style makes it easier to see a constant’s application later in the program
Listing 42-3 shows how you can use a constant The page conveys temperature data for several cities (Presumably, this data is updated on the server and fash-ioned into an array of data when the user requests the page.) For temperatures below freezing, the temperature is shown in a distinctive text style Because the freezing temperature is a constant reference point, it is assigned as a constant
Listing 42-3: Using the const Keyword
<HTML>
<HEAD>
<TITLE>const(ant)</TITLE>
<STYLE TYPE=”text/css”>
.cold {font-weight:bold; color:blue}
TD {text-align:center}
</STYLE>
<SCRIPT LANGUAGE=”JavaScript”>
const FREEZING_F = 32 var cities = [“London”, “Moscow”, “New York”, “Tokyo”, “Sydney”]
var tempsF = [33, 12, 20, 40, 75]
function showData() { var tableData = “”
for (var i = 0; i < cities.length; i++) { tableData += “<TR><TD>” + cities[i] + “</TD><TD “ tableData += (tempsF[i] < FREEZING_F) ? “CLASS=’cold’” : “”
tableData += “>” + tempsF[i] + “</TR>”
const
Trang 2document.getElementById(“display”).innerHTML = tableData
}
</SCRIPT>
</HEAD>
<BODY onLoad=”showData()”>
<H1>The const keyword</H1>
<HR>
<TABLE ID=”temps”>
<TR><TH>City<TH>Temperature</TR>
<TBODY ID=”display”>
</TBODY>
</TABLE>
</BODY>
</HTML>
The constkeyword likely will be adopted in the next version of the ECMA-262
standard and will become part of the JavaScript vernacular in future browsers
var
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Before using any variable, you should declare it (and optionally initialize it with a
value) via the varstatement If you omit the varkeyword, the variable is
automati-cally assigned as a global variable within the current document To keep a variable
local to a function, you must declare or initialize the variable with the varkeyword
inside the function’s braces
If you assign no value to a variable, it evaluates to null Because a JavaScript
variable is not limited to one variable type during its lifetime, you don’t need to
ini-tialize a variable to an empty string or zero unless that initial value helps your
scripting For example, if you initialize a variable as an empty string, you can then
use the add-by-value operator (+=) to append string values to that variable in a
future statement in the document
To save statement lines, you can declare and/or initialize multiple variables with
a single varstatement Separate each varName=valuepair with a comma, as in
var name, age, height // declare as null
var color=”green”, temperature=85.6 // initialize
Variable names (also known as identifiers) must be one contiguous string of
characters, and the first character must be a letter Many punctuation symbols are
also banned, but the underscore character is valid and often is used to separate
multiple words in a long variable name All variable names (like most identifiers in
JavaScript) are case-sensitive, so you must name a particular variable identically
throughout the variable’s scope
var
Trang 3IE/Windows Objects
NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5
Microsoft prides itself on the integration between Web browser functionality and the Windows operating system The linkage between browser and OS is most appar-ent in IE’s facilities for accessing ActiveX objects Microsoft has fashioned several such objects for access to scripters — again, provided the deployment is intended only for Windows versions of Internet Explorer Some objects also exist as a way to expose some Visual Basic Script (VBScript) functionality to JavaScript Because these objects are more within the realm of Windows and ActiveX programming, the details and quirks of working with them from IE/Windows is best left to other venues But in case you are not familiar with these facilities, the following discus-sions introduce the basic set of IE/Windows objects You can find more details at the Microsoft Developer Network (MSDN) Web site; in addition, I provide appropri-ate URLs for your further exploration
The objects mentioned here are the ActiveXObject, Dictionary, Enumerator, FileSystemObject, and VBArrayobjects Microsoft documents these objects as if they are part of the native JScript language However, you can be sure that they will remain proprietary certainly to Internet Explorer, if not exclusively for Windows-only versions
ActiveXObject
ActiveXObjectis a generic object that allows your script to open and access
what Microsoft sometimes calls automation objects An automation object is an
exe-cutable program that might run on the client or be served from a server This can include local applications, such as applications from the Microsoft Office suite, exe-cutable DLLs (dynamic-link libraries), and so on
Use the constructor for the ActiveXObjectto obtain a reference to the object according to the following syntax:
var objRef = new ActiveXObject(appName.className[, remoteServerName])
This JScript syntax is the equivalent of the VBScript CreateObject()method You need to know a bit about Windows programming to determine the application name and the classes or types available for that application For example, to obtain
a reference to an Excel worksheet, use this constructor:
var mySheet = new ActiveXObject(“Excel.Sheet”)
Once you have a reference to the desired object, you must also know the names
of the properties and methods of the object you’ll be addressing You can access much of this information via Microsoft’s developer tools, such as Visual InterDev or the tools that come with Visual Basic These tools enable you to query an object to discover its properties and methods Unfortunately, an ActiveXObject’s proper-ties are not enumerable through a typical JavaScript for-inproperty inspector
ActiveXObject
Trang 4Accessing an ActiveXObject, especially one on the client, involves some
seri-ous security considerations The typical security setup for an IE client prevents
scripts from accessing client applications, at least not without asking the user if it’s
okay to do so While it’s foolhardy to state categorically that you cannot perform
surreptitious inspection or damage to a client without the user’s knowledge
(hack-ers find holes from time to time), it is highly unlikely In a corporate environment,
where some level of access to all clients is desirable, the client may be set up to
accept instructions to work with ActiveX objects when they come from trusted
sources The bottom line is that unless you are well versed in Windows
program-ming, don’t expect the ActiveXObjectto become some kind of magic portal that
enables you to invade the privacy or security of unsuspecting users
For more details, visit http://msdn.microsoft.com/scripting/
jscript/doc/jsobjActiveXObject.htm
Dictionary
While the Dictionaryobject is very helpful to VBScript authors, JavaScript
already provides the equivalent functionality natively A Dictionaryobject
behaves very much like a JavaScript array that has string index values (similar to a
Java hash table), although numeric index values are also acceptable in the
Dictionary Indexes are called keys in this environment VBScript arrays do not
have this facility natively, so the Dictionaryobject supplements the language for
the sake of convenience Unlike a JavaScript array, however, you must use the
vari-ous properties and methods of the Dictionaryobject to add, access, or remove
items from it
You create a Dictionaryobject via ActiveXObjectas follows:
var dict = new ActiveXObject(“Scripting.Dictionary”)
You must create a separate Dictionaryobject for each array Table 42-2 lists the
properties and methods of the Dictionaryobject After you create a blank
Dictionaryobject, populate it via the Add()method for each entry For example,
the following statements create a Dictionaryobject to store U.S state capitals:
var stateCaps = new ActiveXObject(“Scripting.Dictionary”)
stateCaps.Add(“Illinois”, “Springfield”)
You can then access an individual item via the Keyproperty (which, thanks to its
VBScript heritage, looks more like a JavaScript method) One convenience of the
Dictionaryobject is the Keys()method, which returns an array of all the keys in
the dictionary — something that a string-indexed JavaScript array could use
Table 42-2 Dictionary Object Properties and Methods
Count Integer number of entries in the dictionary (read-only)
Item(“key”) Reads or writes a value for an entry whose name is key
Key(“key”) Assigns a new key name to an entry
Continued
Dictionary
Trang 5Table 42-2 (continued)
Add(“key”, value) Adds a value associated with a unique key name
Exists(“key”) Returns Boolean true if key exists in dictionary
Items() Returns VBArray of values in dictionary Keys() Returns VBArray of keys in dictionary
Remove(“key”) Removes key and its value
RemoveAll() Removes all entries
For more details, visit http://msdn.microsoft.com/scripting/jscript/ doc/jsobjDictionary.htm
Enumerator
An Enumeratorobject provides JavaScript with access to collections that other-wise do not allow direct access to their items via index number or name This object isn’t necessary when working with DOM collections, such as document.all, because you can use the item()method to obtain a reference to any member of the collection But if you are scripting ActiveX objects, some of these objects’ meth-ods or properties may return collections that cannot be accessed through this mechanism or the JavaScript for-inproperty inspection technique Instead, you must wrap the collection inside an Enumeratorobject
To wrap a collection in an Enumerator, invoke the constructor for the object, passing the collection as the parameter:
var myEnum = new Enumerator(someCollection)
This enumerator instance must be accessed via one of its four methods to posi-tion a “pointer” to a particular item and then extract a copy of that item In other words, you don’t access a member directly (that is, by diving into the collection with an item number to retrieve) Instead, you move the pointer to the desired posi-tion and then read the item value As you can see from the list of methods in Table 42-3, this object is truly intended for looping through the collection Pointer control
is limited to positioning it at the start of the collection and incrementing its position along the collection by one:
myEnum.moveFirst() for (; !myEnum.atEnd(); myEnum.moveNext()) { val = myEnum.item()
// more statements that work on value }
Enumerator
Trang 6Table 42-3 Enumerator Object Methods
atEnd() Returns true if pointer is at end of collection
item() Returns value at current pointer position
moveFirst() Moves pointer to first position in collection
moveNext() Moves pointer to next position in collection
For more details, visit http://msdn.microsoft.com/scripting/jscript/
doc/jsobjEnumerator.htm
FileSystemObject
Of all the IE/Windows objects, the one whose capabilities most scripters want to
have as a cross-browser native object is FileSystemObject A common wish
among scripters is to be able to save some user-entered data on the client in file
form rather than as a cookie Of course, there can’t be wide-open access to the file
system because unscrupulous scripters could wreak havoc with a user’s system
and privacy — especially in such a well-documented and constant OS file structure
as Windows Netscape Navigator can accomplish many of these same operations
via direct access to Java classes and signed scripts (which obtain the user’s
permis-sion before accessing the file system)
FileSystemObjecthas a large library of methods (and one property) that
scripts with the proper security clearance and permission can use to read and write
files, create and delete files and directories, and, essentially, have its way with the
contents of the client’s hard disk Table 42-4 shows a summary of these methods
FileSystemObject
Trang 7Table 42-4 FileSystemObject Property and Methods
Drives Returns a collection of (disk) Drive objects
(a Drive object has 15 properties)
BuildPath(path, name) Appends name to existing path CopyFile(src, dest[,
overwrite]) Copies file at src path to dest path, optionally
to automatically overwrite existing dest file of
same name
CopyFolder(src, dest[, Copies directory at src path to dest path,
overwrite]) optionally to automatically overwrite existing
destdirectory of same name
CreateFolder(path) Creates folder with name specified in path CreateTextFile(path[, Returns TextStream object after opening an
overwrite[, unicode]]) empty file at path, optionally to overwrite
existing file at path and optionally to save
characters in Unicode (instead of ASCII)
DeleteFile(path[, force]) Deletes file at path, optionally to force deletion
of read-only file
DeleteFolder(path[, force]) Deletes directory at path, optionally to force
deletion of read-only directory
DriveExists(drivespec) Returns true if specified drive exists on client
FileExists(filespec) Returns true if specified file exists
FolderExists(folderspec) Returns true if specified directory exists
GetAbsolutePathName(pathspec) Returns full path based on parameters supplied
in pathspec GetBaseName(filespec) Returns base name of rightmost item in
filespecbut without file extension
GetDrive(drivespec) Returns Drive object referenced by drivespec
(for example, c:\)
GetDriveName(path) Returns name of the drive for a given path GetExtensionName(path) Returns file extension for rightmost item in the
path
GetFile(filespec) Returns File object (a File object has 12
properties and 4 methods of its own)
FileSystemObject
Trang 8Method Description
GetFileName(filespec) Returns the full filename of rightmost item in
pathspec
GetFileVersion(filespec) Returns version number associated with a file
GetFolder(folderspec) Returns Folder object (a Folder object has 15
properties and 4 methods of its own)
GetParentFolderName(path) Returns name of parent directory of path
GetSpecialFolder(type) Returns Folder object of type 0 (Windows), 1
(Windows\System), or 2 (Windows\Temp) GetTempName() Returns a nonsense name for use as a temp
filename
MoveFile(src, dest) Moves src file(s) to dest
MoveFolder(src, dest) Moves src folder(s) to dest
OpenTextFile(path[, iomode[, Returns a TextStream object after opening a file
create[, format]]]) at path for mode (ForReading, ForWriting,
ForAppending ); optionally to create file if not existing; optionally to treat characters as Unicode (TristateTrue), ASCII (TristateFalse), or system default (TristateUseDefault)
As for the basic task of writing some data to a hard disk, the sequence involves
creating an instance of FileSystemObject, opening an output stream for text,
writing content to the file, and closing the file Such a sequence might look like the
following:
function saveLocalData(theData) {
var fsObj = new ActiveXObject(“Scripting.FileSystemObject”)
var theFile = fsObj.CreateTextFile(“c:\\giantco.txt”, true)
theFile.WriteLine(theData)
theFile.Close()
}
The WriteLine()method belongs to the TextStreamobject, which is returned
by FileSystemObject’s CreateTextFile()method You can read more about the
TextStreamobject and the details of the FileSystemObjectat
http://msdn.microsoft.com/scripting/jscript/doc/jsobjtextstream.htm
and http://msdn.microsoft.com/scripting/jscript/doc/
jsobjFileSystem.htm
VBArray
The VBArrayobject provides JavaScript access to Visual Basic safe arrays Such
an array is read-only and is commonly returned by ActiveX objects Such arrays can
be composed in VBScript sections of client-side scripts Visual Basic arrays by their
VBArray
Trang 9very nature can have multiple dimensions For example, the following code creates
a three-by-two VB array:
<SCRIPT LANGUAGE=”VBScript”>
Dim myArray(2, 1) myArray(0, 0) = “A”
myArray(0, 1) = “a”
myArray(1, 0) = “B”
myArray(1, 1) = “b”
myArray(2, 1) = “C”
myArray(2, 2) = “c”
</SCRIPT>
Once you have a valid VB array, you can convert it to an object that the JScript interpreter can’t choke on:
<SCRIPT LANGUAGE=”JavaScript”>
var theVBArray = new VBArray(myArray)
</SCRIPT>
Global variables from one script language block can be accessed by another block, even in a different language But at this point, the array is not in the form of a JavaScript array yet You can either convert it to such via the VBArray.toArray() method or access information about the VBArrayobject through its other methods (described briefly in Table 42-5) Once you convert a VBArrayto a JavaScript array, you can then iterate through the values just like any JavaScript array
Table 42-5 VBArray Object Methods
dimensions() Returns number of dimensions of the original array
getItem(dim1[, dim2[, dimN]]) Returns value at array location defined by
dimension addresses
ibound(dim) Returns lowest index value for a given
dimension toArray() Returns JavaScript array version of VBArray
ubound(dim) Returns highest index value for a given
dimension
When you use the toArray()method and the source array has multiple dimen-sions, values from dimensions after the first “row” are simply appended to the JavaScript array with no nesting structure IE through version 5.5 provides no back-ward conversion from a JavaScript array to a VB array
For more details, visit http://msdn.microsoft.com/scripting/jscript/ doc/jsobjVBArray.htm
VBArray
Trang 10JavaScript
to Work
In This Part
Chapter 43
Data-Entry Validation
Chapter 44
Scripting Java Applets and Plug-ins
Chapter 45
Debugging Scripts
Chapter 46
Security and Netscape Signed Scripts
Chapter 47
Cross-Browser Dynamic HTML Issues
Chapter 48
Internet Explorer Behaviors
Chapter 49
Application: Tables and Calendars
Chapter 50
Application: A Lookup Table
Chapter 51
Application: A “Poor Man’s” Order Form
Chapter 52
Application: Outline-Style Table of Contents
Chapter 53
Application: Calculations and Graphics
Chapter 54
Application: Intelligent
“Updated” Flags
Chapter 55
Application: Decision Helper
Chapter 56
Application: Cross-Browser DHTML Map Puzzle
Chapter 57
Application: Transforming XML Data Islands
V