学习笔记: es6第三版 作者:阮一峰
一. let, const声明的变量只在其所在代码块有效
for (let i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); // i is not defined
二. let, const变量不会提升
console.log(t3);var t3=200;
t3; //200
console.log(t2);let t2=100; // Uncaught ReferenceError: t2 is not defined
三. let, const在块级作用域内存在let, const命令,不受外部影响(暂时性死区)
var t = 123;
if (true) {
t = 'hahahaha'; // Uncaught ReferenceError: Cannot access 't4' before initialization
let t;
}
四. let, const相同作用域内不允许重复声明一个变量
let a = 10;
var a = 1; // Uncaught SyntaxError: Identifier 'a' has already been declared
let a = 10;
let a = 10; // Uncaught SyntaxError: Identifier 'a' has already been declared
function func(arg) {
let arg;
} // Uncaught SyntaxError: Identifier 'arg' has already been declared
五. let, const块级作用域,允许任意嵌套
function f1() {
let n = 5;
if (true) {
let n = 10;
console.log(n); // 10
}
console.log(n); // 5
}
{{{{{
let t9 = 'hahahah';console.log(t9);
{let t9 = 'Hello';console.log(t9);};
}}}}}
六. let, const块级作用域与函数声明
function f() {console.log('I am outside!');}
(function() {
function f() {console.log('I am inside');}
if (false) {}
f();
});
七. do表达式
{
let t = f();
t = t * t + 1;
} // 块级作用域以外获取不到t的值
let x = do {
let t = f();
t * t +1;
}
八. const声明时就要赋值,且赋值后不能改变
const a; // ncaught SyntaxError: Missing initializer in const declaration
const b = '123';
b = '456'; // Uncaught TypeError: Assignment to constant variable.
重要说明:const保证值不变的本质:不是变量的值不得改动,是变量指向的那个内存地址不得改动。对于简单类型的数据(字符串、数值、布尔值)而言,值就保存在变量指向的内存中,所以等同于常量。对于复合类型的数据(主要是【对象】和【数组】)变量指向的内存地址保存的只是指针,const只能保证这个指针是固定的,至于它的数据结构是不能控制的。
const t = {};
t.name = 'alice'; // 属性可以改变,增减,但是不能对整个对象重新赋值
t = {};// Uncaught TypeError: Assignment to constant variable.
const a = []; // 元素可以改变,增减,但是不能对整个数组重新赋值
a.push('hello');
a.length = 0;
a = ['Dave']; // Uncaught TypeError: Assignment to constant variable.
如果真的想冻结对象,无法修改属性值,增减属性
const a = Object.freeze({name:'alice'});
九. 全局变量与顶层对象属性隔离
var t5 = 1;
window.t5; // 1
let t6 = 2;
window.t6; // undifined