1. 类型转换
Value | Context in which value is used | |||
---|---|---|---|---|
String | Number | Boolean | Object | |
Undefined value | "undefined" | NaN | false | Error |
null | "null" | 0 | false | Error |
Nonempty string | As is | Numeric value of string or NaN | true | String object |
Empty string | As is | 0 | false | String object |
0 | "0" | As is | false | Number object |
NaN | "NaN" | As is | false | Number object |
Infinity | "Infinity" | As is | true | Number object |
Negative infinity | "-Infinity" | As is | true | Number object |
Any other number | String value of number | As is | true | Number object |
true | "true" | 1 | As is | Boolean object |
false | "false" | 0 | As is | Boolean object |
Object | toString( ) | valueOf( ) or toString( ) or NaN | true | As is |
2. 值传递和引用传递
The basic rule inJavaScript is this: primitive types are manipulated by value, and referencetypes, as the name suggests, are manipulated by reference. Numbers and booleansare primitive types in JavaScript -- primitive because they consist of nothingmore than a small, fixed number of bytes that are easily manipulated at the low(primitive) levels of the JavaScript interpreter. Objects, on the other hand,are reference types. Arrays and functions, which are specialized types ofobjects, are therefore also reference types. These data types can containarbitrary numbers of properties or elements, so they cannot be manipulated aseasily as fixed-size primitive values can. Since object and array values canbecome quite large, it doesn't make sense to manipulate these types by value,as this could involve the inefficient copying and comparing of large amounts ofmemory.
What about strings? Astring can have an arbitrary length, so it would seem that strings should bereference types. In fact, though, they are usually considered to be primitivetypes in JavaScript simply because they are not objects. Strings don't actuallyfit into the primitive versus reference type dichotomy. We'll have more to sayabout strings and their behavior a little later
值传递:数字,布尔值。
引用传递:对象,数组,函数。
字符串比较特别,属于值传递。
3. 闭包Lexical Scoping and Nested Functions
var x = "global"; function f( ) { var x = "local"; function g( ) { alert(x); } g( ); } f( ); // Calling this function displays "local"
4. Function构造函数 The Function( ) Constructor and Function Literals
var y = "global"; function constructFunction( ) { var y = "local"; return new Function("return y"); // Does not capture the local scope! } // This line displays "global", because the function returned by the // Function( ) constructor does not use the local scope. Had a function // literal been used instead, this line would have displayed "local". alert(constructFunction()( )); // Displays "global"