1. Trang chủ >
  2. Giáo án - Bài giảng >
  3. Tin học >

Chapter 3. JavaScript Syntax and Statements

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.5 MB, 505 trang )


50



Part I  JavaWhat? The Where, Why, and How of JavaScript



Chapter 4 provides much more information about variables and their naming conventions.

For now, remember that you must pay attention to the case when you write a variable name

in JavaScript.



White Space

For the most part, JavaScript ignores white space, which is the space between statements

in JavaScript. You can use spaces, indenting, or whatever coding standards you prefer to

make the JavaScript more readable. There are some exceptions to this rule, however. Some

keywords, such as return, can be misinterpreted by the JavaScript interpreter when they’re

included on a line by themselves. You’ll see an example of this problem a little later in this

chapter.

Making programs more readable is a good enough reason to include white space. Consider

the following code sample. It includes minimal white space and indenting.

function cubeme(incomingNum) {

if (incomingNum == 1) {

return "What are you doing?";

} else {

return Math.pow(incomingNum,3);

}

}

var theNum = 2;

var finalNum = cubeme(theNum);

if (isNaN(finalNum)) {

alert("You should know that 1 to any power is 1.");

} else {

alert("When cubed, " + theNum + " is " + finalNum);

}



Now consider the same code with indenting. (You can find this code, named example1.txt, in

the Chapter 3 sample code in the companion content.)

function cubeme(incomingNum) {

if (incomingNum == 1) {

return "What are you doing?";

} else {

return Math.pow(incomingNum,3);

}

}

var theNum = 2;

var finalNum = cubeme(theNum);

if (isNaN(finalNum)) {

alert("You should know that 1 to any power is 1.");

} else {

alert("When cubed, " + theNum + " is " + finalNum);

}







Chapter 3  JavaScript Syntax and Statements



51



The second code sample performs just like the first, but it’s easier to read and follow—at

least it appears so to me! I find that it takes a short amount of time to actually write code,

but several years to work with it. When I visit the code a year later, I’m much happier when

I’ve made the code more readable and easier to follow.



Comments

Speaking of creating more readable code and maintaining that code over the long term,

comments are your friends. Code that seems blatantly obvious now won’t be nearly so obvious the next time you look at it, especially if a lot of time has passed since you wrote it.

Comments can be placed into JavaScript code in two ways: multiline and single-line.

A multiline comment in JavaScript will look familiar to you if you’ve coded in the C programming language. A multiline comment begins and ends with /* and */ respectively, as this code

example shows:

/* This is a multiline comment in JavaScript

It is just like a C-style comment insofar as it can

span multiple lines before being closed. */



A single-line comment begins with two front slashes (//) and has no end requirement,

because it spans only a single line. An example is shown here:

// Here is a single line comment.



Using multiple single-line comments is perfectly valid, and I use them for short comment

blocks rather than use the multiline comment style previously shown. For example, look at

this block of code:

// Here is another comment block.

// This one uses multiple lines.

// Each line must be preceded with two slashes.



Tip  You may find it quicker to use the two-slash method for small comments that span one



line or a few lines. For larger comments, such as those at the beginning of a program or script,

the multiline comment style is a better choice because it makes adding or deleting information

easier.



Semicolons

Semicolons are used to delineate expressions in JavaScript. Technically, semicolons are not

required for most statements and expressions. However, the subtle problems that you can

encounter when you don’t use semicolons add unnecessary errors and hence unnecessary



52



Part I  JavaWhat? The Where, Why, and How of JavaScript



debugging time. In some instances, the JavaScript interpreter inserts a semicolon when you

may not have wanted one at all. For example, consider this statement:

return

(varName);



In all likelihood, you wanted to write:

return(varName);



But JavaScript, acting on its own, inserts a semicolon after the return statement, making the

code appear like this to the JavaScript interpreter:

return;

(varName);



This code won’t work; the interpreter will misunderstand your intentions. If you used this

code in a function, it would return undefined to the caller, which is unlikely to be what you

want. This is an example where free use of white space is not allowed—you can’t successfully

use line breaks (explained in the next section) to separate the return keyword from the value

that it’s supposed to return.

You’ll find programming in JavaScript much easier if you use semicolons as a rule rather than

try to remember where you might not have to use them.

But you definitely shouldn’t use semicolons in one instance: when using loops and conditionals.

Consider this bit of code:

if (a == 4)

{

// code goes here

}



In this case, you wouldn’t use a semicolon at the end of the if statement. The reason is that

the statement or block of statements in opening and closing braces that follows a conditional

is part of the conditional statement, in this case, the if statement. A semicolon marks the

end of the if statement, and if improperly placed, dissociates the first part of the if statement

from the rest of it. For example, the following code is wrong (the code within the braces will

execute regardless of whether a equals 4):

if (a == 4);

{

// code goes here

}



Tip  When opening a loop or function, skip the semicolons.







Chapter 3  JavaScript Syntax and Statements



53



Line Breaks

Related closely to white space and even to semicolons in JavaScript are line breaks, sometimes called carriage returns. Known in the official ECMA-262 standard as “Line Terminators,”

these characters separate one line of code from the next. Like semicolons, the placement

of line breaks matters. As you saw from the example in the previous section, placing a line

break in the wrong position can result in unforeseen behavior or errors.

Not surprisingly, the most common use of line breaks is to separate individual lines of code

for readability. You can also improve readability of particularly long lines of code by separating them with line breaks. However, when doing so, be aware of issues like the one illustrated

by the return statement cited earlier, in which an extra line break can have unwanted effects

on the meaning of the code.



Placing JavaScript Correctly

JavaScript can be placed in a couple of locations within a Hypertext Markup Language

(HTML) page: in the section, or between the and tags.

The most common location for JavaScript has traditionally been between the and

tags near the top of the page. However, placing the



Older browsers may not parse the CDATA section correctly. This problem can be worked

around by placing the CDATA opening and closing lines within JavaScript comments, like this:



54



Part I  JavaWhat? The Where, Why, and How of JavaScript





When you place the actual JavaScript code in a separate file (as you learned how to do in

Chapter 2, “Developing in JavaScript”), you don’t need to use this ugly CDATA section at all.

You’ll probably discover that for anything but the smallest scripts, defining your JavaScript in

separate files—usually with the file extension .js—and then linking to those scripts within the

page, is desirable. Chapter 2 showed this in full detail, but here’s a reminder of how you link

to a file using the src attribute of the

A Chapter 3 Example

















3. Save the page, and then run the code or view the webpage in a browser. You’ll receive

an alert like this:



58



Part I  JavaWhat? The Where, Why, and How of JavaScript



The code in this example incorporates the code from the earlier example into a full HTML

page, including a DOCTYPE declaration. The code declares a function, cubeme(), within the

of the document, like this:

function cubeme(incomingNum) {

if (incomingNum == 1) {

return "What are you doing?";

} else {

return Math.pow(incomingNum,3);

}

}



This code accepts an argument called incomingNum within the function. An if/then decisional

statement is the heart of the function. When the incoming number equals 1, the function returns the text string, “What are you doing?” When, on the other hand, the incoming number

is not equal to 1, the Math.pow method is called, passing the incomingNum variable and the

integer 3 as arguments. The call to Math.pow raises the incoming number to the power of 3,

and this value is then returned to the calling function. This call is shown again in Chapter 4.

All the previous code was placed within the of the document so it can be called by

other code, which is just what we’re going to do. The browser then renders the of

the document, which includes another bit of JavaScript code. This next bit of code sets a variable, theNum, equal to the integer 2:

var theNum = 2;



The code then calls the previously defined cubeme() function using the theNum variable as

an argument. You’ll notice that the variable finalNum is set to receive the output from the

call to the cubeme() function, as follows:

var finalNum = cubeme(theNum);



The final bit of JavaScript on the page is another if/then decisional set. This code checks to

determine whether the returned value, now contained in the finalNum variable, is a number.

It does this by using the isNaN() function. If the value is not a number, an alert is displayed

reflecting the fact that 1 was used as the argument. (Of course, there could be other reasons

this isn’t a number, but bear with me here and follow along with my example.) If the return

value is indeed a number, the number is displayed, as you saw in the alert() dialog box shown

in the preceding step 3.







Chapter 3  JavaScript Syntax and Statements



59



JavaScript’s New Strict Mode

ECMA-262 version 5 introduced a strict variant, commonly referred to as strict mode, which

adds enhanced error checking and security. For example, to help fight against mistyped variable names, variable declarations require the use of the var keyword. Additionally, changes to

the eval() function and other areas help JavaScript programmers to improve their code.

Strict mode is enabled with the following syntax, which is very similar to syntax used in Perl:

"use strict";



Strict mode is locally scoped, meaning that it can be enabled globally, by placing the use

strict line at the beginning of the script; or it can be enabled only within a function, by

placing the line within the function itself, like so:

function doSomething() {

"use strict";

// function’s code goes here.

}



One strict mode enhancement that will help catch typographical errors is the prevention of

undeclared variables. All variables in strict mode need to be instantiated prior to use. For

example, consider this code:

"use strict";

x = 4;



// Produces a syntax error



The code would create an error condition because the variable x hasn’t been declared with

the var keyword, as it is here:

"use strict";

var x = 4;



// This syntax is ok



Of the notable security enhancements that strict mode provides is the change to how the

eval() function is handled. In strict mode, eval() cannot instantiate a new variable or function

that will be used outside of the eval() statement. For example:

"use strict";

eval("var testVar = 2;");

alert(testVar);



// Produces a syntax error.



60



Part I  JavaWhat? The Where, Why, and How of JavaScript



In the code example, a syntax error would be produced because strict mode is enabled and

the testVar variable isn’t available outside of the eval() statement.

Strict mode also prevents the duplication of variable names within an object or function call:

"use strict";

var myObject = {

testVar: 1,

testVar: 2

};



The previous code would produce a syntax error in strict mode because testVar is set twice

within the object’s definition.

Like other aspects of ECMA-262 version 5, strict mode may not be available in all browsers

and likely won’t be available for older browsers. For more information about ECMA-262 version 5 as well as a full implementation, see http://besen.sourceforge.net/.



Exercises





1. Which of the following are valid JavaScript statements? (Choose all that apply.)







a. if (var == 4) { // Do something }







b. var testVar = 10;







c. if (a == b) { // Do something }







d. testVar = 10;







e. var case = “Yes”;







2. True or False: Semicolons are required to terminate every JavaScript statement.







3. Examine this bit of JavaScript. What is the likely result? (Assume that the JavaScript

declaration has already taken place and that this code resides properly within the

section of the page.)

var orderTotal = 0;

function collectOrder(numOrdered) {

if (numOrdered > 0) {

alert("You ordered " + orderTotal);

orderTotal = numOrdered * 5;

}

return orderTotal;

}



Xem Thêm
Tải bản đầy đủ (.pdf) (505 trang)

×