ES6作用域 let&const

塊作用域(即大括號內的作用域)
  • es5中作用域:全局作用域、函數作用域
  • es6新增了塊作用域
  • 離開了大括號,可以理解爲塊作用域的生命週期結束
  • es6強制開啓嚴格模式(“use strict”)
  • 嚴格模式下,變量未聲明則不能引用,否則報錯
function test(){
	for(var i=1; i<3; i++ ){
		console.log(i)//循環輸出1,2
	}
	console.log(i)//3
}
test()
//1
//2
//3
function test(){
	for(let i=1; i<3; i++ ){
		console.log(i)//循環輸出1,2
	}
	console.log(i)//報錯 i is not defined
}
test()
//1
//2
//報錯 i is not defined
let
  • 不能重複定義變量
let a = 1;
let a = 2;
//不能重複定義變量
const
  • const聲明時,必須賦值
  • const聲明的常量無法修改
  • const聲明的引用類型時,可以修改屬性
  • const 聲明的引用類型時,不變的是指針,但可以改變引用類型的屬性
const a = '123'
a = '555' //報錯,常量不能變
const tt;
const obj = {x: 213}
obj.x = 456
console.log(obj)//{x:456}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章