Javascript Further

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"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章