《深入理解ES6》笔记(1)

  var 声明的变量会提升到作用域顶部。变量初始值为undefined。

  let声明只能在块内访问,且禁止重声明。通常将let声明语句放在封闭代码块的顶部,以便整个代码块都可以访问。

//1
let a=33;
a=34;//此时报错,let禁止重声明


//2
function getName(){//只有此函数内部可以访问b值
    let  b=233;
    .....
}

  const声明的是常量,值一旦被设定后不能更改。const声明的常量只能在当前代码块内有效,一旦执行到块外后立即被销毁。同样禁止重声明。const声明不允许修改绑定,但是允许修改值。

//1
const a=33;

//此处报错,const禁止重声明
a=34;


//2

const person={
    name:'jiaxiaonuo'
    };

//正常执行
person.name='robin';

//报错
person={
    name:'nuonuo';
    };

  let可以应用于for循环。const不建议应用在for循环。

for(let i=0;i<10;i++){
    console.log(i);
    };

  let和const可以在for-in、for-of循环中使用。

var arr=[],
    fruits={
        apple:true,
        orange:true,
        banana:true
    };
for(let key in fruits){
    arr.push(function(){
    console.log(key);
    });
}
arr.forEach(function(func){
    func();
});
var arr=[],
    fruits={
        apple:true,
        orange:true,
        banana:true
    };
for(const key in fruits){
    arr.push(function(){
    console.log(key);
    });
}
arr.forEach(function(func){
    func();
});

  var会覆盖一个已经存在的全局变量,而let和const不能覆盖全局变量,知识遮蔽它。

var RegExp='this is me';
console.log(window.RegExp);            //this is me


let RegExp='haha';
console.log(RegExp);              //haha
console.log(RegExp===window.RegExp);    //false


const ncz='lili';
console.log(ncz);             //lili
console.log(ncz===window.ncz);             //false

  默认使用const,只有确实需要改变变量的值时使用let.

原文地址:https://www.cnblogs.com/jiaxiaonuo/p/7247367.html