文档库 最新最全的文档下载
当前位置:文档库 › 外文翻译英文

外文翻译英文

CHAPTER 16
JavaScript Functions, Objects, and
Arrays
Just like PHP, JavaScript offers access to functions and objects. In fact, JavaScript is
actually based on objects, because—as you’ve seen—it has to access the DOM, which
makes every element of an HTML document available to manipulate as an object.
The usage and syntax are also quite similar to those of PHP, so you should feel right at
home as I take you through using functions and objects in JavaScript, as well as con-
ducting an in-depth exploration of array handling.
JavaScript Functions
In addition to having access to dozens of built-in functions (or methods) such as
write, which you have already seen being used in document.write, you can easily create
your own functions. Whenever you have a more complex piece of code that is likely to
be reused, you have a candidate for a function.
Defining a Function
The general syntax for a function is:
function function_name([parameter [, ...]])
{
statements
}
The first line of the syntax indicates that:
? A definition starts with the word function.
? A name follows that must start with a letter or underscore, followed by any number
of letters, digits, dollar symbols, or underscores.
? The parentheses are required.
? One or more parameters, separated by commas, are optional (indicated by the
square brackets, which are not part of the function syntax).
Function names are case-sensitive, so all of the following strings refer to different func-
tions: getInput, GETINPUT, and getinput.
In JavaScript there is a general naming convention for functions: the first letter of each
word in a name is capitalized except for the very first letter, which is lowercase. There-
fore, of the previous examples, getInput would be the preferred name used by most
programmers. The convention is commonly referred to as bumpyCaps.
The opening curly brace starts the statements that will execute when you call the func-
tion; a matching curly brace must close it. These statements may include one or more
return statements, which force the function to cease execution and return to the calling
code. If a value is attached to the return statement, the calling code can retrieve it.
The arguments array
The arguments array is a member of every function. With it, you can determine the
number of variables passed to a function and what they are. Take the example of a
function called displayItems. Example 16-1 shows one way of writing it.
Example 16-1. Defining a function

When you call this script in your browser, it will display the following:
Dog
Cat
Pony
Hamster
Tortoise
All of this is fine, but what if you

wanted to pass more than five items to the function?
Also, reusing the document.write call multiple times instead of employing a loop is
wasteful programming. Luckily, the arguments array gives you the flexibility to handle
a variable number of arguments. Example 16-2 shows how you can use it to rewrite the
example in a much more efficient manner.
Example 16-2. Modifying the function to use the arguments array

Note the use of the length property, which you already encountered in the previous
chapter, and also how the array displayItems.arguments is referenced using the variable
j as an offset into it. I also chose to keep the function short and sweet by not surrounding
the contents of the for loop in curly braces, as it contains only a single statement.
Using this technique you now have a function that can take as many (or as few) argu-
ments as you like and act on each argument as you desire.
Returning a Value
Functions are not used just to display things. In fact, they are mostly used to perform
calculations or data manipulation and then return a result. The function fixNames in
Example 16-3 uses the arguments array (discussed in the previous section) to take a
series of strings passed to it and return them as a single string. The “fix” it performs is
to convert every character in the arguments to lowercase except for the first character
of each argument, which is set to a capital letter.
Example 16-3. Cleaning up a full name

When called with the parameters “the”, “DALLAS”, and “CowBoys”, for example, the
function returns the string “The Dallas Cowboys”. Let’s walk through the function.
The function first initializes the temporary (and local) variable s to the empty string.
Then a for loop iterates through each of the passed parameters, isolating the parame-
ter’s first character using the charAt method and converting it to uppercase with thetoUpperCase method. The various methods shown in this example are all built-in to
JavaScript and available by default.
Then the substr method is used to fetch the rest of each string, which is converted to
lowercase using the toLowerCase method. A fuller version of the substr method here
would specify how many characters are part of the substring as a second argument:
substr(1, (arguments[j].length) - 1 )
In other words, this substr method says, “Start with the character at position 1 (the
second character) and return the rest of the str

ing (the length minus one).” As a nice
touch, though, the substr method assumes that you want the rest of the string if you
omit the second argument.
After the whole argument is converted to our desired case, a space character is added
to the end and the result is appended to the temporary variable s.
Finally, the substr method is used again to return the contents of the variable s, except
for the final space—which is unwanted. This is removed by using substr to return the
string up to, but not including, the final character.
This example is particularly interesting in that it illustrates the use of multiple properties
and methods in a single expression. For example:
fixNames.arguments[j].substr(1).toLowerCase()
You have to interpret the statement by mentally dividing it into parts at the periods.
JavaScript evaluates these elements of the statement from left to right as follows:
1. Start with the name of the function itself: fixNames.
2. Extract element j from the array arguments representing fixNames arguments.
3. Invoke substr with a parameter of 1 to the extracted element. This passes all but
the first character to the next section of the expression.
4. Apply the method toLowerCase to the string that has been passed this far.
This practice is often referred to as method chaining. So, for example, if the string
“mixedCASE” is passed to the example expression, it will go through the following
transformations:
mixedCase
ixedCase
ixedcase
One final reminder: the s variable created inside the function is local, and therefore
cannot be accessed outside the function. By returning s in the return statement, we
made its value available to the caller, which could store or use it any way it wanted.
But s itself disappears at the end of the function. Although we could make a function
operate on global variables (and sometimes that’s necessary), it’s much better to just
return the values you want to preserve and let JavaScript clean up all the other variables
used by the function.
Returning an Array
In Example 16-3, the function returned only one parameter, but what if you need to
return multiple parameters? This can be done by returning an array, as in Example 16-4.
Example 16-4. Returning an array of values

Here the variable words is automatically defined as an array and populated with the
returned result of a call to the function fixNames. Then a for loop iterates through the
array and displays each member.
As for the fixNames function, it’s almost identical to Example 16-3, except that th

e
variable s is now an array, and after each word has been processed it is stored as an
element of this array, which is returned by the return statement.
This function enables the extraction of individual parameters from its returned values,
like the following (the output from which is simply “The Cowboys”):
words = fixNames("the", "DALLAS", "CowBoys")
document.write(words[0] + " " + words[2])
JavaScript Objects
A JavaScript object is a step up from a variable, which can contain only one value at a
time, in that objects can contain multiple values and even functions. An object groups
data together with the functions needed to manipulate it.
Declaring a Class
When creating a script to use objects, you need to design a composite of data and code
called a class. Each new object based on this class is called an instance (or occurrence)
of that class. As you’ve already seen, the data associated with an object are called its
properties, while the functions it uses are called methods.
Let’s look at how to declare the class for an object called User that will contain details
about the current user. To create the class, just write a function named after the class.
This function can accept arguments (I’ll show later how it’s invoked) and can create
properties and methods for the objects in that class. The function is called a constructor.
Example 16-5 shows a constructor for the class User with three properties: forename,
username, and password. The class also defines the method showUser.
Example 16-5. Declaring the User class and its method

The function is different from other functions we’ve seen so far in two ways:
? It refers to an object named this. When the program creates an instance of User
by running this function, this refers to the instance being created. The same func-
tion can be called over and over with different arguments, and will create a new
User each time with different values for the properties forename, and so on.
? A new function named showUser is created within the function. The syntax shown
here is new and rather complicated, but its purpose is to tie showUser to the User
class. Thus, showUser comes into being as a method of the User class.
The naming convention I have used is to keep all properties in lowercase and to use at
least one uppercase character in method names, following the bumpyCaps convention
mentioned earlier in the chapter.
Example 16-5 follows the recommended way to write a class constructor, which is to
include methods in the constructor function. However, you can al

so refer to functions
defined outside the constructor, as in Example 16-6.
Example 16-6. Separately defining a class and method

I show you this form because you are certain to encounter it when perusing other
programmers’ code.
Creating an Object
To create an instance of the class User, you can use a statement such as the following:
details = new User("Wolfgang", "w.a.mozart", "composer")
Or you can create an empty object, like this:
details = new User()
and then populate it later, like this:
details.forename = "Wolfgang"
https://www.wendangku.net/doc/a78026910.html,ername = "w.a.mozart"
details.password = "composer"
You can also add new properties to an object, like this:
details.greeting = "Hello"
You can verify that adding such new properties works with the following statement:
document.write(details.greeting)
Accessing Objects
To access an object, you can refer to its properties, as in the following two unrelated
example statements:
name = details.forename
if (https://www.wendangku.net/doc/a78026910.html,ername == "Admin") loginAsAdmin()
So to access the showUser method of an object of class User, you would use the following
syntax, in which the object details has already been created and populated with data:
details.showUser()
Assuming the data supplied earlier, this code would display:
Forename: Wolfgang
Username: w.a.mozart
Password: composer
The prototype Keyword
The prototype keyword can save you a lot of memory. In the User class, every instance
will contain the three properties and the method. Therefore, if you have 1,000 of these
objects in memory, the method showUser will also be replicated 1,000 times. However,
because the method is identical in every case, you can specify that new objects should
refer to a single instance of the method instead of creating a copy of it. So, instead of
using the following in a class constructor:
this.showUser = function()
you could replace it with this:
User.prototype.showUser = function()
Example 16-7 shows what the new constructor would look like.
Example 16-7. Declaring a class using the prototype keyword for a method


相关文档
相关文档 最新文档