分类: Javascript

Professional Javascript For Web Developers – Language Basics






Language Basics

The primary method of inserting JavaScript into an HTML page is via the “script” element.
There are six attributes for the script element:
➤ async — Optional. Indicates that the script should begin downloading immediately but should not prevent other actions on the page such as downloading resources or waiting for other scripts to load. Valid only for external script files.
➤ charset — Optional. The character set of the code specified using the src attribute. This attribute is rarely used, because most browsers don’t honor its value.
➤ defer — Optional. Indicates that the execution of the script can safely be deferred until after the document’s content has been completely parsed and displayed. the defer attribute is supported only for external script files
➤ language — Deprecated. Originally indicated the scripting language being used by the code block (such as “JavaScript”, “JavaScript1.2”, or “VBScript”). Most browsers ignore this attribute; it should not be used.
➤ src — Optional. Indicates an external file that contains code to be executed.
➤ type — Optional. Replaces language; indicates the content type (also called MIME type) of the scripting language being used by the code block.
There are two ways to use the “script” element:
– embed JavaScript code directly into the page
– Include JavaScript from an external file.To include JavaScript from an external file, the src attribute is required.
HTML 4.01 defines an attribute named defer for the “script” element. The purpose of defer is to indicate that a script won’t be changing the structure of the page as it executes.

<head> 
     <title>Example HTML Page</title> 
     <script type=”text/javascript” defer src=”example1.js”></script> 
     <script type=”text/javascript” defer src=”example2.js”></script> 
</head>
Even though the "script" elements in this example are included in the document <head>, they will not be executed until after the browser has received the closing  tag
syntax

Case-sensitivity The first concept to understand is that everything is case-sensitive; variables, function names, and operators are all case-sensitive
An identifier is 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 ($).
ECMAScript uses C-style comments for both single-line and block comments.

//single line comment
/* * This is a multi-line * Comment */

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
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

variable

ECMAScript variables are loosely typed, meaning that a variable can hold any type of data. Every variable is simply a named placeholder for a value. To define a variable, use the var operator (note that var is a keyword) followed by the variable name
It’s important to note that using the var operator 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 var means that the variable is destroyed as soon as the function exits, as shown here:
It is, however, possible to define a variable globally by simply omitting the var operators follows:

      function test(){
              message = “hi”; //global variable 
      } 
      test(); 
      alert(message); //”hi”

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;

There are five simple data types (also called primitive types) in ECMAScript:

Undefined

The Undefined type has only one value, which is the special value undefined. When a variable is declared using var but not initialized, it is assigned the value of undefined

Null

The Null type is the second data type that has only one value: the special value null. Logically, a null value is an empty object pointer, which is why typeof returns “object” when it’s passed a null value

Boolean

The Boolean type is one of the most frequently used types in ECMAScript and has only two literal values: true and false. These values are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.Note that the Boolean literals true and false are case-sensitive, so True and False (and other mixings of uppercase and lowercase) are valid as identifiers but not as Boolean values.

Number

To support the various types of numbers, there are several different number literal formats.The most basic number literal format is that of a decimal integer.To create a hexadecimal literal, you must make the first two characters 0x (case insensitive), followed by any number of hexadecimal digits (0 through 9, and A through F). Letters may be in uppercase or lowercase. Here’s an example:

 
var hexNum1 = 0xA; //hexadecimal for 10 
var hexNum2 = 0x1f; //hexedecimal for 31

To define a floating-point value, you must include a decimal point and at least one number after the decimal point.Because storing floating-point values uses twice as much memory as storing integer values,
When there is no digit after the decimal point, the number becomes an integer. Likewise, if the number being represented is a whole number (such as 1.0), it will be converted into an integer, as in this example:

var floatNum1 = 1.; //missing digit after decimal - interpreted as integer 1 
var floatNum2 = 10.0; //whole number - interpreted as integer 10

There is a special numeric value called NaN, short for Not a Number, which is used to indicate when an operation intended to return a number has failed

There are three functions to convert nonnumeric values into numbers:
– the Number() casting function,
The Number() function performs conversions based on these rules:
➤ When applied to Boolean values, true and false get converted into 1 and 0, respectively.
➤ When applied to numbers, the value is simply passed through and returned.
When applied to null, Number() returns 0. When applied to undefined, Number() returns NaN.
When applied to strings, the following rules are applied:

  var num1 = Number(“Hello world!”); //NaN 
  var num2 = Number(“”); //0 
  var num3 = Number(“000011”); //11 
  var num4 = Number(true); //1
  

– the parseInt() function,
The parseInt() function examines the string much more closely to see if it matches a number pattern

var num1 = parseInt(“1234blue”); //1234 
var num2 = parseInt(“”); //NaN 
var num3 = parseInt(“0xA”); //10 
var num4 = parseInt(22.5); //22
var num5 = parseInt(“70”); //70
var num6 = parseInt(“0xf”);  //15 

All of the different numeric formats can be confusing to keep track of, so parseInt() provides a second argument: the radix (number of digits) to use.

var num = parseInt(“0xAF”, 16); //175
var num1 = parseInt(”AF”, 16); //175 
var num2 = parseInt(”AF”); //NaN
-----------------------------------------------------
var num1 = parseInt(“10”, 2); //2 - parsed as binary
var num2 = parseInt(“10”, 8); //8 - parsed as octal 
var num3 = parseInt(“10”, 10); //10 - parsed as decimal
var num4 = parseInt(“10”, 16); //16 - parsed as hexadecimal

– the parseFloat() function
The parseFloat() function works in a similar way to parseInt(), looking at each character starting in position 0. It also continues to parse the string until it reaches either the end of the string or a character that is invalid in a floating-point number

String

The String data type represents a sequence of zero or more 16-bit Unicode characters. Strings can be delineated by either double quotes (“) or single quotes (‘).
A string using double quotes is exactly the same as a string using single quotes. Note, however, that a string beginning with a double quote must end with a double quote, and a string beginning with a single quote must end with a single quote
The length of any string can be returned by using the length property
In most cases, toString() doesn’t have any arguments. However, when used on a number value, toString() actually accepts a single argument: the radix in which to output the number

var num = 10; 
alert(num.toString());  //”10”
alert(num.toString(2)); //”1010”
alert(num.toString(8)); //”12”
alert(num.toString(10));//”10”  
alert(num.toString(16));//”a” 
Object

Objects are created by using the new operator followed by the name of the object type to create.

var o = new Object();
Operations

The identically equal operator is represented by three equal signs (===) and returns true only if the operands are equal without conversion, as in this example:

var result1 = (“55” == 55); //true - equal because of conversion 
var result2 = (“55” === 55); //false - not equal because different data types

var result1 = (“55” != 55); //false - equal because of conversion 
var result2 = (“55” !== 55); //true - not equal because different data types

Conditional Operator The conditional operator is one of the most versatile in ECMAScript, and it takes on the same form as in Java, which is as follows:

variable = boolean_expression ? true_value : false_value;
while

The do-while statement is a post-test loop
meaning that the escape condition is evaluated only after the code inside the loop has been executed. The body of the loop is always executed at least once before the expression is evaluated

The while statement is a pretest loop. This means the escape condition is evaluated before the code inside the loop has been executed.

for

The for-in statement is a strict iterative statement. It is used to enumerate the properties of an object.
And here’s an example of its usage:

   for (var propName in window) { 
        document.write(propName); 
   }

The break statement exits the loop immediately, forcing execution to continue with the next statement after the loop.

The continue statement, on the other hand, exits the loop immediately, but execution continues from the top of the loop.

 var num = 0; 
 for (var i=1; i < 10; i++) { 
     if (i % 5 == 0) { 
     break; 
     } 
  num++; 
 } 
 alert(num); //4 
(when 5 -> break. jump out of for loop, force continue with the next statement)
--------------------------
 var num = 0; 
 for (var i=1; i < 10; i++) { 
     if (i % 5 == 0) { 
     continue; 
     } 
   num++; 
  } 
  alert(num); //8 
(5 and 10 - continue -> back to loop exit before num++)

When i reaches a value of 5, the loop is exited before num is incremented, but execution continues with the next iteration, when the value is 6. The loop then continues until its natural completion, when i is 10. The final value of num is 8 instead of 9, because one increment didn’t occur because of the continue statement.

with

The with statement was created as a convenience for times when a single object was being coded to over and over again, such as in this example:

var qs = location.search.substring(1); 
var hostName = location.hostname; 
var url = location.href;
----------------------
with(location){ 
   var qs = search.substring(1); 
   var hostName = hostname; 
   var url = href; 
}
(更新:for Performance try not to use with)

Screen Shot 2013-12-14 at 12.52.33 am

Function

Functions are the core of any language, because they allow the encapsulation of statements that can be run anywhere and at any time.
This function can then be called by using the function name, followed by the function arguments enclosed in parentheses (and separated by commas, if there are multiple arguments)
Function arguments in ECMAScript don’t behave in the same way as function arguments in most other languages. An ECMAScript function doesn’t care how many arguments are passed in, nor does it care about the data types of those arguments. Just because you define a function to accept two arguments doesn’t mean you can pass in only two arguments.
arguments in ECMAScript are represented as an array internally. The array is always passed to the function, but the function doesn’t care what (if anything) is in the array. If the array arrives with zero items, that’s fine; if it arrives with more, that’s okay too. In fact, there actually is an arguments object that can be accessed while inside a function to retrieve the values of each argument that was passed in.
The arguments object acts like an array (though it isn’t an instance of Array) in that you can access each argument using bracket notation (the first argument is arguments[0], the second is arguments[1], and so on) and determine how many arguments were passed in by using the length property.

    function howManyArgs() { 
        alert(arguments.length); 
    } 
    howManyArgs(“string”, 45); //2 
    howManyArgs(); //0 
    howManyArgs(12); //1

ECMAScript functions cannot be overloaded in the traditional sense
If two functions are defined to have the same name in ECMAScript, it is the last function that becomes the owner of that name.
Functions in ECMAScript behave differently than functions in other languages:
➤ There is no need to specify the return value of the function since any function can return any value at any time.
➤ Functions that don’t specify a return value actually return the special value undefined.
➤ There is no such thing as a function signature, because arguments are passed as an array containing zero or more values.
➤ Any number of arguments can be passed into a function and are accessible through the arguments object.
➤ Function overloading is not possible because of the lack of function signatures.




发表评论

Webmentions

  • Professional Javascript For Web Developers – 复习笔记(Language Basics) | Ian's Blog

    […] Up topic: – Language Basics (syntax,variable and operations) – Variables, Scope, And Memory – Reference […]