JavaScript's data types can be combined to create more sophisticated structures.
JavaScript functions are an important method for organizing your scripts.
function
keyword, before they are used or called:function dayTime() { |
|
Function definitions load with the rest of document, but they are not executed until called, as in the last line in the example above.
Function definitions are therefore usually placed in the head of the document, ready for later use.
return
statement, whose execution will terminate the function call.undefined
value if:return
statement doesn't have a parameter, orreturn
statement isn't executed, and the function reaches the closing brace.function quadranomial(x, a, b, c) { |
|
When a function is called with parameters, the data is copied to the corresponding variables in the function definition.
Therefore, with one exception (objects, discussed below), a variable used in a function call can't be changed by the function.
If a function is called with fewer parameters than in its definition, the extra parameters are set to null
.
If a function is called with more parameters than in its definition, the extra parameters are unnamed but are available through the function's parameter array (discussed below).
var
keyword.var
keyword's use outside of a function results in a variable with global scope, visible anywhere in a document, including inside of functions.typeof
operator will describe all functions as one might expect:
document.write(typeof quadranomial)
Note that this is different than:
document.write(typeof quadranomial(1, 2, 3, 4))
void
operator can be used to throw away the result:
document.write(typeof void quadranomial(1, 2, 3, 4))
The precedence and associativity table previously described the
void
operator.
JavaScript objects are the key to interacting with documents.
object.member
and often by object.subobject.member
, etc.
<script language="JavaScript">
function checkCollege(college) {
if (college.value.toLowerCase() != 'amherst College' &&
college.value.toLowerCase() != 'amherst') {
college.value = 'Not Acceptable!'
} else {
college.value = 'Amherst College'
}
}
</script>
<form name="CollegeInput">
<input name="College" type="text" value="Type Your College Here"
size="22" onChange="checkCollege(this)">
</form>
This script can be interpreted as follows:
CollegeInput
corresponds to an object called document.CollegeInput
.document.CollegeInput.College
, which in context can be referenced by the synonym this
, simplifying many expressions.this.name
, this.type
, this.value
, and this.size
, as well as an event handler this.onchange()
.this.value
changes in response.this.onchange()
notices the new text, and executes its action, a function statement.checkCollege(this)
copies the field object reference this
to a parameter named college
, now a reference to the same text-input-field object.college.value
, which is a string.college.value.toLowerCase()
, which applies the obvious transformation to the object college.value
.college.value
, by a simple assignment, thereby again changing the contents of the text field (though not in a way that triggers the event handler this time).Question: What other document objects have we encountered already? What properties did they have?
typeof
operator will describe all objects as being the same kind:
document.writeln(typeof document.CollegeInput)
document.write(typeof document.CollegeInput.College)
document.CollegeInput.College.not = 'Not Acceptable!'
document.CollegeInput.College.checkCollege = checkCollege()Note also that some properties in a predefined object might be read-only.
Netscape has published a nice comparison of objects in C++/Java and JavaScript.
ssCellA1 = { column:0, row:0, name:cr2name, value:32.4 }
document.write('<table width="150" border="1" cellspacing="1" cellpadding="1">')
document.write('<tr><td width="50" align="center"></td>')
document.write('<td width="100" align="center"><b>A</b></td>')
document.write('</tr><tr><td align="center"><b>1</b></td>')
document.write('<td align="center">')
document.write(ssCellA1.name() + ' == ' + ssCellA1.value)
document.write('</td></tr></table>')
new
keyword, the Object
prototype, and subsequent property initializations:
ssCellB1 = new Object()
ssCellB1.column = 1
ssCellB1.row = 0
ssCellB1.name = cr2name
ssCellB1.value = ''
document.write('<table width="250" border="1" cellspacing="1" cellpadding="1">')
document.write('<tr><td width="50" align="center"></td>')
document.write('<td width="100" align="center"><b>A</b></td>')
document.write('<td width="100" align="center"><b>B</b></td>')
document.write('</tr><tr><td align="center"><b>1</b></td>')
document.write('<td align="center">')
document.write(ssCellA1.name() + ' == ' + ssCellA1.value)
document.write('</td><td align="center">')
document.write(ssCellB1.name() + ' == ' + ssCellB1.value)
document.write('</td></tr></table>')
new
keyword:
function SSCell(column, row, value) {
this.column = column
this.row = row
this.name = cr2name
this.value = value
}
ssCellA2 = new SSCell(0, 1, -27)
ssCellB2 = new SSCell(1, 1, 7.5)
document.write('<table width="250" border="1" cellspacing="1" cellpadding="1">')
document.write('<tr><td width="50" align="center"></td>')
document.write('<td width="100" align="center"><b>A</b></td>')
document.write('<td width="100" align="center"><b>B</b></td>')
document.write('</tr><tr><td align="center"><b>1</b></td>')
document.write('<td align="center">')
document.write(ssCellA1.name() + ' == ' + ssCellA1.value)
document.write('</td><td align="center">')
document.write(ssCellB1.name() + ' == ' + ssCellB1.value)
document.write('</tr><tr><td align="center"><b>2</b></td>')
document.write('<td align="center">')
document.write(ssCellA2.name() + ' == ' + ssCellA2.value)
document.write('</td><td align="center">')
document.write(ssCellB2.name() + ' == ' + ssCellB2.value)
document.write('</td></tr></table>')
Occasionally, though, you may wish to explicitly delete an object:
delete ssCellB2 |
|
You can even delete a particular object property, leaving the rest of the object:
document.write('ssCellA2.value a(n) ' + typeof ssCellA2.value + ' value.<br>') |
|
The precedence and associativity table previously described the delete
operator.
form
object document.CollegeInput.College
above.with
statement provides a solution, by designating an "object root" with which JavaScript associates otherwise undefined variables:
/* Previously defined:
|
|
document.write('ssCellA1.value = ' + ssCellA1.value + '<br>') |
|
Note that in JavaScript 1.0, you can also reference an object's properties by numeric index, i.e. ssCellB1[0]
is the same as ssCellB1['column']
is the same as ssCellB1.column
.
This is no longer true in newer versions of JavaScript, with the sole exception of certain document elements that we will talk about later.
Using associative arrays and an object-specific variation of the for
statement, called the for-in
statement, it's possible to examine all of an object's properties:
document.write('The members of the object ssCellA1 are:<br>')
for (member in ssCellA1) {
document.write('ssCellA1.' + member + ' = ' + ssCellA1[member] + '<br>')
}
Note that in this statement, the variable
member
is set to the name of each of the object's members as a string.
JavaScript does not have an explicit array type, but you can create an array object.
Array
prototype:fiveColleges = new Array('Amherst College', |
|
Note that, as elsewhere in the C family, the first element of an array is indexed by 0, and the last by n - 1, where n is the length of the array.
Arrays constructed this way come with a length
property that dynamically changes as elements are appended.
Arrays may be constructed using several alternative formats:
JavaScript Array Object Construction |
|||
Format |
Definition |
Examples |
|
new Array() |
Empty array; |
squares = new Array() |
1.1 |
|
|||
new Array(n) |
Array with n elements, |
sparse = new Array(5) |
1.1 |
|
|||
new Array(a1,a2,
) |
Array with argument list of elements |
fiveColleges = new Array('Amherst College', 'Hampshire College',
'Mount Holyoke College', 'Smith College',
'University of Massachusetts', 'Williams College') |
1.1 |
|
|||
[a1,a2,
] |
"Literal" array with bracketed list of elements |
sports = ['baseball', 'basketball', 'football', 'lacrosse', 'soccer'] |
1.2 |
|
Note that there is an ambiguity with respect to a single numeric argument to Array()
, as it could be either an empty array with that length (the second construction above) or an array with a single numeric element (the third construction above); generally speaking, the former is used.
A special case is for Array(1)
, which will have length one in either case; in JavaScript 1.1 that element is undefined, but in subsequent versions it is set to "1" to avoid confusion.
length
property:function genArray(n) { |
|
An important consideration is that for such arrays, the length
property is identical to its zeroth element.
In addition, the length
property of such an array doesn't change if you extend the array, so its use is discouraged.
delete
operator:delete fiveColleges[5] |
|
Note that what has really happened is that the element has simply lost its value, but it still exists, so the array length doesn't change.
threeColleges[1] = 3 |
|
colleges = [ fiveColleges, // Row 0 threeColleges ] // Row 1 |
|
[Note that this array is not actually rectangular...]
With a rectangular array of cells we can now build a spreadsheet object:
function ssWrite() { |
|
Even JavaScript's core data types and functions are objects in their own right!
toString()
, which converts them to human-readable form:
document.write('true is rendered as "' + true.toString() + '"') |
|
toString()
is automatically referenced whenever a non-string is used in a string context, e.g. by document.write()
to print objects.
For numbers, toString()
has an optional radix argument to specify the base of the output:
document.write('12 can be rendered as "' + (12).toString() + '"') |
|
Note that the number here must be placed in parentheses to
distinguish the object member operator '.' from a decimal point.
toString()
:
function ssToString() { |
|
Function objects have some additional useful properties and methods.
arguments
array:
function sum() { |
|
arity
property:
// Do you remember how many arguments the quadranomial function used?
|
|
Function
.Function
can be used to define a so-called "anonymous" function (which typically does have an assigned name, though often an abstract one):
f = new Array(5) for (i = 0; i < 5; i++) { document.write(f[3](4, 2)) |
|
To work with JavaScript, no special tools are required, just a text editor to write scripts into a .html file (the source view of Dreamweaver can also be used), and a web browser to view the result.