变量和常量的范围

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 关键字的变量)是全局变量。

请参见

概念

未定义的值

其他资源

JScript 变量和常量