ES6 let与const

一、简介

ES2015(ES6) 新增加了两个重要的 JavaScript 关键字: let 和 const。

let 声明的变量只在 let 命令所在的代码块内有效。

const 声明一个只读的常量,一旦声明,常量的值就不能改变。

二、let用法

1.基本用法

for循环的计数器,很合适使用let命令

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

console.log(i);
// ReferenceError: i is not defined

2.let特性

不存在变量提升
let 不存在变量提升,var 会变量提升

console.log(a);  //ReferenceError: a is not defined
let a = "apple";
 
console.log(b);  //undefined(b声明已提升但未赋值)
var b = "banana";

块级作用域

{
  let a = 0;
  var b = 1;
}
a  // ReferenceError: a is not defined
b  // 1

暂时性死区
只要块级作用域内存在let、const命令,它所声明的变量就“绑定”(binding)这个区域,不再受外部的影响。

var tmp = 123;

if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
}

不能重复声明

let a = 1;
let a = 2;
var b = 3;
var b = 4;
a  // Identifier 'a' has already been declared
b  // 4

三、const用法

1.基本用法

const声明的变量不得改变值,这意味着,const一旦声明变量,就必须立即初始化,不能留到以后赋值。

const foo;// SyntaxError: Missing initializer in const declaration

const PI = 3.1415;
PI // 3.1415
PI = 3;// TypeError: Assignment to constant variable.

2.本质

const实际上保证的,并不是变量的值不得改动,而是变量指向的那个内存地址所保存的数据不得改动。对于简单类型的数据(数值、字符串、布尔值),值就保存在变量指向的那个内存地址,因此等同于常量。但对于复合类型的数据(主要是对象和数组),变量指向的内存地址,保存的只是一个指向实际数据的指针,const只能保证这个指针是固定的(即总是指向另一个固定的地址),至于它指向的数据结构是不是可变的,就完全不能控制了。因此,将一个对象声明为常量必须非常小心。

const foo = {};

// 为 foo 添加一个属性,可以成功
foo.prop = 123;
foo.prop // 123

// 将 foo 指向另一个对象,就会报错
foo = {}; // TypeError: "foo" is read-only

四、ES6声明变量的六种方式

ES5 只有两种声明变量的方法:var、function

ES6在ES5基础上新增:let、const、import、class

猜你喜欢

转载自blog.csdn.net/qq_41466440/article/details/111468029