Thứ Tư, 21 tháng 8, 2013

VARIABLES

 Every variable is simply a named placeholder for a value.
var message;
This code defines a variable named messagethat can be used to hold any value.
var message = “hi”;
Here, messageis defined to hold a string value of “hi”. Doing this initialization doesn’t mark
the variable as being a string type; it is simply the assignment of a value to the variable. It is still
possible to not only change the value stored in the variable but also change the type of value, such
as this:
var message = “hi”;
message = 100; //legal, but not recommended
In this example, the variable message is first defined as having the string value “hi”and then
overwritten with the numeric value 100. Though it’s not recommended to switch the data type that
a variable contains, it is completely valid in ECMAScript.
It’s important to note that using the varoperator to define a variable makes it local to the scope in
which it was defined. For example, defining a variable inside of a function using varmeans that the
variable is destroyed as soon as the function exits, as shown here:
function test(){
var message = “hi”; //local variable
}
test();
alert(message); //error!
Here, the message variable is defined within a function using var. The function is called test(),
which creates the variable and assigns its value. Immediately after that, the variable is destroyed so
the last line in this example causes an error. It is, however, possible to define a variable globally by
simply omitting the varoperator as follows:
function test(){
message = “hi”; //global variable
}
test();
alert(message); //”hi”
By removing the var operator from the example, the message variable becomes global. As soon as the function test()is called, the variable is defined and becomes accessible outside of the function once it has been executed.
Although it’s possible to define global variables by omitting the varoperator, this approach is not recommended. Global variables defined locally are hard to maintain and cause confusion, because it’s not immediately apparent if the omission of varwas intentional. Strict mode throws a ReferenceErrorwhen an undeclared variable is assigned a value.If you need to define more than one variable, you can do it using a single statement, separating each variable (and optional initialization) with a comma like this:
var message = “hi”, 
found = false,
age = 29;
Here, three variables are defined and initialized. Because ECMAScript is loosely typed, variable initializations using different data types may be combined into a single statement. Though inserting line breaks and indenting the variables isn’t necessary, it helps to improve readability.When you are running in strict mode, you cannot define variables named evalor arguments. Doing so results in a syntax error.

KEYWORDS AND RESERVED WORDS

break do instanceof typeof
case else new var
catch finally return void
continue for switch while
debugger* function this with
default if throw
delete in try

 The following is the complete list of reserved words
abstract enum int short
boolean export interface static
byte extends long super
char final native synchronized
class float package throws
const goto private transient
debugger implements protected volatile
double import public

The fifth edition shrinks down the list of reserved words when running in nonstrict mode to the following:
class enum extends super
const export import

When running in strict mode, the fifth edition also places reserved word restrictions on the following:
implements package public
interface private static
let protected yield


SYNTAX JAVASCRIPT

Case-sensitivity
The first concept to understand is that everything is case-sensitive; variables, function names, and operators are all case-sensitive, meaning that a variable named testis different froma variable named Test. Similarly, typeof can’t be the name of a function, because it’s a keyword (described in the next section); however, typeOf is a perfectly valid function name.
Identif 
An identifieris the name of a variable, function, property, or function argument. Identifiers may be one or more characters in the following format:The first character must be a letter, an underscore (_), or a dollar sign ($).All other characters may be letters, underscores, dollar signs, or numbers.Letters in an identifier may include extended ASCII or Unicode letter characters such as À and Æ, though this is not recommended.
By convention, ECMAScript identifiers use camel case, meaning that the first letter is lowercase and each additional word is offset by a capital letter, like this:
firstSecond
myCar
doSomethingImportant
Although this is not strictly enforced, it is considered a best practice to adhere to the built-in ECMAScript functions and objects that follow this format
Comments 
ECMAScript uses C-style comments for both single-line and block comments. A single-line comment begins with two forward-slash characters, such as this:
//single line comment
A block comment begins with a forward slash and asterisk (/*) and ends with the opposite (*/), as in this example:
/*
* This is a multi-line
* Comment
*/
Note that even though the second and third lines contain an asterisk, these are not necessary and are added purely for readability. (This is the format preferred in enterprise applications.)
Strict Mode
ECMAScript 5 introduced the concept of strict mode. Strict mode is a different parsing and execution model for JavaScript, where some of the erratic behavior of ECMAScript 3 is addressed and errors are thrown for unsafe activities. To enable strict mode for an entire script, include the following at the top:
“use strict”;
Although this may look like a string that isn’t assigned to a variable, this is a pragma that tells supporting JavaScript engines to change into strict mode. The syntax was chosen specifically so as not to break ECMAScript 3 syntax.You may also specify just a function to execute in strict mode by including the pragma at the top of the function body:
function doSomething(){
“use strict”;
//function body
}
Strict mode changes many parts of how JavaScript is executed, and as such, strict mode distinctions are pointed out throughout the book. Internet Explorer 10+, Firefox 4+, Safari 5.1+, Opera 12+, and Chrome support strict mode.
Statements
Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes
the parser determine where the end of a statement occurs, as in the following examples:
var sum = a + b //valid even without a semicolon - not recommended
var diff = a - b; //valid - preferred
Even though a semicolon is not required at the end of statements, it is recommended to always include one. Including semicolons helps prevent errors of omission, such as not finishing what you were typing, and allows developers to compress ECMAScript code by removing extra white space (such compression causes syntax errors when lines do not end in a semicolon). Including semicolons also improves performance in certain situations, because parsers try to correct syntax errors by inserting semicolons where they appear to belong.
Multiple statements can be combined into a code block by using C-style syntax, beginning with a left curly brace ({) and ending with a right curly brace (}):
if (test){
test = false;
alert(test);
}
Control statements, such as if, require code blocks only when executing multiple statements. However, it is considered a best practice to always use code blocks with control statements, even if there’s only one statement to be executed, as in the following examples:
if (test)
alert(test); //valid, but error-prone and should be avoided
if (test){ //preferred
alert(test);
}
Using code blocks for control statements makes the intent clearer, and there’s less chance for errors
when changes need to be made.

Language Basics Javascript


  • Reviewing syntax
  • Working with data types
  • Working with fl ow-control statements
  • Understanding functions
Of particular concern to early browsers was the graceful degradation of pages when the browser didn’t support JavaScript. To that end, the <noscript>element was created to provide alternate content for browsers without JavaScript.
Here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Page</title>
<script type=”text/javascript” defer=”defer” src=”example1.js”></script>
<script type=”text/javascript” defer=”defer” src=”example2.js”></script>
</head>
<body>
<noscript>
<p>This page requires a JavaScript-enabled browser.</p>
</noscript>
</body>
</html>
In this example, a message is displayed to the user when the scripting is not available. For scriptingenabled browsers, this message will never be seen even though it is still a part of the page.

Document modes

Standards mode is turned on when one of the following doctypes is used:
<!-- HTML 4.01 Strict -->
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”
“http://www.w3.org/TR/html4/strict.dtd”>

<!-- XHTML 1.0 Strict -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<!-- HTML5 -->
<!DOCTYPE html>
Almost standards mode is triggered by transitional and frameset doctypes, as follows:
<!-- HTML 4.01 Transitional -->
<!DOCTYPE HTML PUBLIC
“-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>

<!-- HTML 4.01 Frameset -->
<!DOCTYPE HTML PUBLIC
“-//W3C//DTD HTML 4.01 Frameset//EN”
“http://www.w3.org/TR/html4/frameset.dtd”>

<!-- XHTML 1.0 Transitional -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<!-- XHTML 1.0 Frameset -->
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Frameset//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd”>

Deprecated Syntax

When the <script>element was originally introduced, it marked a departure from traditional HTML parsing. Special rules needed to be applied within this element, and that caused problems for browsers that didn’t support JavaScript (the most notable being Mosaic). Nonsupporting browsers would output the contents of the <script>element onto the page, effectively ruining the page’s appearance.Netscape worked with Mosaic to come up with a solution that would hide embedded JavaScript code from browsers that didn’t support it. The final solution was to enclose the script code in an HTML comment, like this:
<script><!--function sayHi(){
alert(“Hi!”);
}
//--></script>
Using this format, browsers like Mosaic would safely ignore the content inside of the <script>tag, and browsers that supported JavaScript had to look for this pattern to recognize that there was indeed JavaScript content to be parsed.Although this format is still recognized and interpreted correctly by all web browsers, it is no longer necessary and should not be used. In XHTML mode, this also causes the script to be ignored because it is inside a valid XML comment.