lynxerzhang / JSSkills

MIT License
0 stars 0 forks source link

js中使用var或者let来声明变量有什么不同? #1

Open lynxerzhang opened 6 years ago

lynxerzhang commented 6 years ago

这个帖子很好的说明了两者的区别,现在整理如下:

1. 在function外声明的变量, let无法通过window来访问到

var canfound = 2;
let cannotFound = 2;
console.log(window.canfound); //2
console.log(window.cannotFound); //undefined

2. let 无法被重新声明

let canNotBeRedeclaration = 1;
let canNotBeRedeclaration = 2; 
//Identifier 'canNotBeRedeclaration' has already been declared

var canBeRedeclaration = 1;
var canBeRedeclaration = 2;  
console.log(canBeRedeclaration); //2

3. let在function中的作用域

//let
function testletScope() {
  //无法访问i  ReferenceError: i is not defined
  for(let i = 0; i < 5; i ++){
     //可以访问i
  }
  //无法访问i ReferenceError: i is not defined
}

//var
function testvarScope() {
  //由于变量提升,i为undefined 
  for(var i = 0; i < 5; i ++){
     //可以访问i
  }
  //可以访问i
}