1.const声明一个只读的常量。一旦声明,常量的值就不能改变。
const PI = 3.14
PI = 2.14
2.对于const来说,只声明不赋值,就会报错。
const PI;
3.const的作用域与let命令相同:只在声明所在的块级作用域内有效。
if(true){
const MAX = 5
}
MAX
4.const命令声明的常量也是不提升,同样存在暂时性死区,只能在声明的位置后面使用。
if(true){
MAX = 6
const MAX = 5
}
5.const声明的常量,也与let一样不可重复声明。
var a = 'hello'
let b = 'word'
const a = 'hello'
const b = 'word'
6.本质:常量student 储存的是一个地址,这个地址指向一个对象。不可变的只是这个地址,即不能把student 指向另一个地址,但对象本身是可变的,所以依然可以为其添加新属性。
const student = {}
student.age = 12
student.name = 'tom'
student = {} // 将 foo 指向另一个对象,就会报错 TypeError: "student " is read-only
7.将const 指向冻结对象,添加新属性不起作用,严格模式还会报错
const student = Object.freeze({})
student.a = 123
8.除了将对象本身冻结,对象的属性也应该冻结。下面是一个将对象彻底冻结的函数。
var constantize = (obj) => {
Object.freeze(obj);
Object.keys(obj).forEach((key, i) => {
if (typeof obj[key] === 'object') {
constantize(obj[key]);
}
})
}
const a = {}
a.b = 123
constantize(a)
a.b = 456 //thirdScriptError