在javascript es6中,提到了一個新的概念,叫塊級做用域,塊級做用域就是用大括號包起來的來的代碼塊。javascript
let,const是塊級元素,var是局部做用域(局部做用域是function函數裏可見),let和const的區別見以下代碼段java
function varTest() { var x = 1; if (true) { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 }
const與let的區別在於const是它是不變的,而let是可變的。es6
可是對於const只是對於基本數據類型的值或者是引用數據類型的引用對象是不可變的,而引用對象裏面的屬性依然是可變的,若是想要引用對象裏面的屬性值都不可見怎麼辦呢?能夠使用Object.freeze(),使用方法以下:函數
const wes = Object.freeze(person);
在全局做用域中,var會自動建立爲一個全局對象(window)的屬性,而let不會,相關代碼以下this
var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined
let不容許重定義,不容許先使用,後定義,相關代碼以下code
let foo; let foo; // SyntaxError thrown.
console.log(foo); // ReferenceError let foo = 2;
想快速瞭解更多的Javascript es6新特性,請點擊以下連接:http://es6-features.org/對象