javascript的let,var

在javascript中变量的声明方式var,let,const等会让人糊涂,这里简简单的总结一下:

var 是function scope ,而 let 是 block scope, function scope 的意思是变量是声明在函数内部,而block scope 意思是变量声明在 for循环,if,else 等块当中。

下面的是function scope.

function iHaveScope() {
  // local function scope
  function iHaveNestedScope() {
    // nested local function scope
  }
}

下面的是block scope.

{ var a } // undefined object in a block scope
if (3 == '3') {
  // block scope for the if statement
}
for (var i=0; i<10; i++) {
  // block scope for the for statement
}

而var 在 block scope 和function scope 里表现的不一样,在function scope 里声明的变量在function 外面不能使用,而在block scope 里声明的变量在 block 外面可以使用。

function iHaveScope() {
  var secret = 42;
}
secret; // ReferenceError: secret is not defined (in this scope)
for (var i=0; i<10; i++) {
  // block scope for the for statement
}
console.log(i) // => 10 (why oh why)

 因此当我们用var 来在一个块中定义变量会有问题,因此需要一个关键字使变量只能在那个block 里面起作用。

for (let i=0; i<10; i++) {
  // block scope for the for statement
}
console.log(i) // ReferenceError: i is not defined (D'oh!)

global scope

下面我们说一说当变量通过var,let 在全局声明的时候的区别.

当一个变量通过var 来全局声明的时候是挂在window object ,但 通过let 来声明的时候不会挂在 window object。

var varVariable = “this is a var variable”;
let letVariable = “this is a let variable”;

console.log(window.varVariable); //this is a var variable
console.log(window.letVariable); //undefined

当我们打印通过let 来声明的变量的时候会出出现错误,因为它们不能全局被全局得到。

如果需要更加深入的了解请参考这里:var vs let,var and let 以及 var and let global use.

发布了83 篇原创文章 · 获赞 18 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Abudula__/article/details/84140906
今日推荐