变量声明和作用域规则

在编程中,变量的范围决定了该变量可以在程序中使用的位置,以及哪些函数和对象可以访问该变量。

通常,变量可以具有局部范围或全局范围。 在代码块内声明的变量具有局部作用域,并且只能由同一块内的其他代码访问。 一旦退出声明的块,该变量将超出范围。 另一方面,全局变量可从当前正在执行的脚本(或程序)中的任何位置访问,并且通常会持续整个程序的整个生命周期。

var

使用var关键字声明变量时,作用域如下:

  • 如果在任何函数外部声明了该变量,则该变量在全局范围内可用。
  • 如果在函数内声明了变量,则从声明点到函数定义结束为止,变量都是可用的。

让我们看一些示例

function varScope() {
   var a = 2;
   console.log(a); // outputs  2
}

console.log(a); // ReferenceError, a is not accessible outside the function.

让我们来看另一个例子。

function varScope() {
   var a = 2;
   if(true) {
      var a =  "Jamie"; //change the value of a inside the "if" block
      console.log(a); //prints "Jamie"
   }
   console.log(a); //prints "Jamie": outside the "if" block, a still maintains the updated value 
   //a being function scoped, the (re-) declaration inside the if statement overwrote the previous value of a
   //when we assigned it a new value inside the conditional statement
}
console.log(a); // ReferenceError, again, a is not accessible outside the function.

最后,让我们看一看

function forScope() {
   for(var i = 0; i < 5; i++) {
      console.log(i); //prints the values 0 through 4;
   }
   console.log(i); //prints 5;
}

刚刚发生了什么? 在for循环中,我们声明并初始化i变量。 然后在循环内部,我们从0进行迭代,i的值小于5,则在每次迭代时都将i加1。 当i的值等于5时,条件i <5评估为false,从而终止循环。 但是,由于i是使用var声明的,因此其范围从声明的位置扩展到函数的末尾。 因此,即使在循环之后,我们也可以访问i的最新值,在这种情况下为5。

let

使用let关键字声明的变量具有三个重要特征。

  • 它们是块作用域的
  • 在分配之前无法访问它们
  • 无法在同一范围内重新声明它们

让我们使用一些示例来了解这意味着什么。

function  letScope() {
   let a = 5;

   if  (true) {
      let a = "Jamie";  // using let creates a new a variable inside the "if" block
      console.log(a); //  prints "Jamie"
   }

   console.log(a); // 5,  outside the if block, the outer a shines through
}
console.log(a); // ReferenceError, a is not accessible outside the function.

const

使用const关键字声明的变量具有使用let关键字声明的变量的所有特征,以及一个重要的区别特征

  • 无法重新赋值
const a = 2;
a = 3 // Error, reassignment is not allowed

你可能感兴趣的:(javascript)