變數和常數範圍

JScript 有三個範圍:全域、區域和類別。 如果您在函式或類別定義之外宣告變數或常數,就成為全域變數,其值可在整個程式中存取和修改。 如果您在函式定義內宣告變數,則該變數就是區域變數。 每次執行函式時,就會建立它再予以摧毀,而且這個變數不能在函式之外存取。 如果您在類別定義的內部宣告變數,這個變數可以在類別內部使用,但不能直接從全域範圍存取。 如需詳細資訊,請參閱類別架構的物件

討論

C++ 等語言也有「區塊範圍」,任何一組大括號 ({}) 都能定義新的範圍。 JScript 不支援區塊範圍。

區域變數可以與全域變數使用相同的名稱,但是它是完全不同且各自獨立的。 所以,變更其中一種變數的值並不會對另一種變數產生作用。 在宣告區域變數的函式內部,只有區域版本才有意義。 這稱為「可視性」。

// Define two global variables.
var name : String = "Frank";
var age : int = "34";

function georgeNameAge() {
   var name : String; // Define a local variable.
   name = "George";   // Modify the local variable.
   age = 42;          // Modify the global variable.
   print(name + " is " + age + " years old.");
}

print(name + " is " + age + " years old.");
georgeNameAge();
print(name + " is " + age + " years old.");

這個程式的輸出內容,顯示區域變數的值可以修改,而不會影響到全域變數的值。 然而從函式內部變更全域變數,就會影響全域範圍中的該值。

Frank is 34 years old.
George is 42 years old.
Frank is 42 years old.

在執行任何程式碼之前,JScript 會先處理變數和常數宣告,如此一來宣告是否位於條件式區塊或某些其他建構內就沒關係了。 只要 JScript 找到所有變數和常數,它就會執行函式中的程式碼。 這表示區域常數值在遇到常數宣告陳述式之前,一直是未定義值,除非在函數中指派變數值,否則區域變數值是未定義的。

有時,這會產生非預期的行為。 請看下列程式。

var aNumber = 100;
var anotherNumber = 200;
function tweak() {
   var s = "aNumber is " + aNumber + " and ";
   s += "anotherNumber is " + anotherNumber + "\n";
   return s;
   if (false)  {
      var aNumber;                // This statement is never executed.
      aNumber = 123;              // This statement is never executed.
      const anotherNumber = 42;   // This statement is never executed.
   } // End of the conditional.
} // End of the function definition.

print(tweak());

這個程式的輸出內容為:

aNumber is undefined and anotherNumber is undefined

您也許認為 aNumber 是 100 或 123,anotherNumber 是 200 或 42,但這兩個值都是 undefined。 由於 aNumber 和 anotherNumber 都是定義在區域範圍,因此相同的名稱將遮蔽掉全域變數和常數。 但由於初始化區域變數和常數的程式碼永遠不會執行,因此它們的值是 undefined

快速模式中需要明確變數宣告。 如果快速模式已關閉,就需要隱含變數宣告。 在函式內部隱含宣告的變數 (也就是設定運算式左側沒有 var 關鍵字的變數) 是全域變數。

請參閱

概念

Undefined 值

其他資源

JScript 變數和常數