Javascript - Functions and Objects
Written on 06/29/12 at 14:06:43 EST by GentleGiant
JavascriptingThe basic statements, expressions, and operators that were discussed at the beginning of this chapter are what computer scientists usually call primitives. Primitives are the building blocks from which more complex elements of a program are constructed. The for, while, and if control structures represent the next higher level of organization in JavaScript. Each of these control structures deals with blocks of code whose execution is controlled by the various conditional tests and other clauses. The for, while, and if statements are all block structured.

Functions and objects represent the highest level of organization within the JavaScript language. We will spend many chapters learning how to make effective use of these concepts. The purpose of this section is to introduce them and describe their basic features.

Functions
A function is a block of code that has a name. Whenever that name is used the function is called, which means that the code within that function is executed. Functions may also be called with values, known as parameters, which may be used inside the body of the function. Functions serve two purposes. A function is an organizational tool, in the sense that it permits you to perform the same operation without simply copying the same code.

The second purpose of JavaScript functions is to link actions on a Web page with JavaScript code. Mouse clicks, button presses, text selections, and other user actions can call JavaScript functions by including suitable tags in the HTML source for the page.

Event handler functions are explored in Chapter 3, particularly in the "Events and HTML Tags" section.

The syntax for a function statement in JavaScript is as follows:

function Name ( listofparams ) {
    body
}

The function's Name is given immediately after the function keyword. All function names should be unique, and also should not conflict with any of the statement names which JavaScript itself uses (known as the reserved words). You cannot have a function named while, for example, and you should not have two functions both named UserHelp. The listofparams is a comma-separated list of the values that are passed into the function. These are referred to as the function's parameters, or arguments. This list may be empty, indicating that the function does not use any arguments (often called a void function). The function's body is the set of statements that make up the function. Listing 2.9 shows a function that adds up all the integers starting at 1 and ending at a value given as the sole argument.

Listing 2.9 A Summation function

function summation ( endval ) {

    var thesum = 0;               // this variable will hold the sum

    for ( var iter = 1; iter < endval; iter++ ) {
         thesum += iter;          // add the integer into the sum
    }                         // end of the for loop
    return( thesum );          // return the sum
}

This function does the same task that came up in the discussions of the while and for statements earlier in this chapter. Now that it has been written as a function, this code never needs to be repeated again. Any time you wish to form the sum 1 + 2 + ... + N, you can simply call the function, as summation(N), and it will perform the task. Notice that the endval parameter is used as the argument to the function.

When the function is called, as summation(14) for example, the actual value 14 is used for endval within the function. The function then executes the for statement, with iter < 14 as its termination condition, adding in each successive value into the variable thesum. When the for loop is done, the function executes the return statement. This causes the function to give the value inside the return statement back to the caller. This means that if we write

var sum14;
sum14 = summation(14);
the variable sum14 is set to the value returned by the summation function when endval is given the value 14, namely 105. Functions can return any type of value, and are not restricted to returning integers.

There are several things to notice about this example. First of all, the variables thesum and iter, which are declared within the body of this function, are local variables. This means that they are only known within the body of this function, and are therefore completely unknown outside it. It is quite possible, even likely, that there are many functions, all of which have a local variable named iter. All these various iters are unrelated. Changing the value of one of these iters would not affect any of the others. This is why the return statement is necessary; it is the only way to communicate the work of the function back to the caller.

This same restriction applies to the parameter endval as well. The arguments to a function may not be changed within that function. We could well have written endval = 15 just before the return statement in listing 2.9. This statement would do nothing; it certainly would not change the caller's 14 into a 15. It might seem like every function would always have a return statement. This is not the case, however, since it is possible for a function to have side effects without actually returning a value. This happens by referencing external objects, which are our next topic.

Objects
Functions are used to provide a uniform method for organizing code. Objects serve the same purpose for data. Up to this point the only data items we have seen are simple variables declared with var. Each of these typeless quantities can only hold a single value of some sort at a time. Objects provide the ability to hold multiple values, so that a group of related data elements can be associated with one another.

What JavaScript calls an object is called a data structure (or class) in many other languages. As with JavaScript functions, there are two aspects to JavaScript objects: creating them and using them. For the moment we will defer the question of how to create objects and concentrate on how they are used. We will also see that a JavaScript capable browser will provide a number of its own, built-in objects.

A Javascrypt object is made up of a set of component parts, which are called its properties, or members. Suppose you have an object named appt which you are using to organize your appointments. The appointment object might have properties that specify the date and time of the appointment, as well as the name of the person with whom the appointment will take place. It might also have a general descryption field to remind you of the purpose of this meeting. Thus, you can imagine that the appt object will have the following properties:

day
month
time
who
why
Each of the properties of the appt object are referenced using the dot operator (.). Thus, appt.month refers to the month property and appt.why gives us the reason for the appointment. These references may appear on both the right and left sides of an expression; we may get their values and also set them. Listing 2.10 shows a code fragment that tests the value of appt and displays a message about a current appointment.

Listing 2.10 Using the appt Object
if ( appt.day == Today ) {
    document.write('<BR>You have an appointment today<BR>');
    document.write('See ' + appt.who + ' at ' + appt.time<BR>');
    document.write(appt.why + '<BR>');
}

This example assumes that the variable Today has somehow been initialized with today's date, so that the equality test with appt.day is only true for today's appointments. If the test does succeed then the three statements in the if block are executed. Each of these references document.write. The document object is a built-in object of the Netscape Navigator browser. This object has a member known as write, which is actually a function. Functional members of JavaScript objects are known as methods. This particular method takes a string and displays it on the current Web page.

Each of the three strings that are passed to document.write are constructed using + as a string concatenation operator. Each of them references one or more properties of the appt object in order to provide meaningful messages to the user. Each also includes <BR>, the HTML construction for a line break. This ability to directly issue HTML directives is one of the most powerful aspects of JavaScript, as it allows the programmer to dynamically modify the contents of Web pages using JavaScript functions and objects.

Once you learn more about the Date object, in "The Date Object" section of chapter 5, you will be able to construct a much more satisfying version of this example. Even at this stage, however, the advantage of object-based programming should be apparent. Rather than carrying about many variables, you can use objects instead. Each object can contain all the variables of interest to a particular idea. It can also contain method functions that perform related work. Objects can even contain other objects, so that you can organize your data in a hierarchical structure. Subsequent chapters explore these ideas in much greater detail.

News and Comments Brought to you by: Geeks and Bloggers
The comments are owned by the poster. We aren't responsible for its content.