ES2015 新增了兩個變量修飾關鍵字:javascript
letjava
const程序員
它們都是塊級別的,那什麼是塊?簡單的來講,塊就是一組花括號中間的部分。後端
Varcode
爲了理解let咱們先從var提及,以下代碼:ip
function checkStatus(status) { if (status) { var statusLabel = 'ok'; console.log(statusLabel); } else { console.log(statusLabel); } } checkStatus(true); checkStatus(false);
在 Chrome Console 中運行後,得到結果:作用域
ok undefined
咱們在false條件中加入一行代碼:it
function checkStatus(status) { if (status) { var statusLabel = 'ok'; console.log(statusLabel); } else { console.log(statusLabel); console.log(abc);//執行後會輸出: Uncaught ReferenceError: abc is not defined(…) } } checkStatus(true); checkStatus(false);
對於初次接觸JavaScript的後端程序員來講,會以爲很是奇怪,在傳入false的時候爲何獲得的statusLabel是undefined而不是變量未定義?而嘗試輸出abc就能獲得變量未定義的錯誤呢?io
這是由於在JavaScript中使用var定義的變量會被預先提高到做用域最開始的地方(這裏就是這個function), 在這個例子中也就是if位置的上面, 代碼就能夠寫成:console
function checkStatus(status) { var statusLabel; if (status) { statusLabel = 'ok'; console.log(statusLabel); } else { console.log(statusLabel); } }
這是JavaScript獨有的, 因此以前定義變量的好的習慣就是在全部可能會使用的地方以前定義好,如此,纔不會產生各類奇怪奇怪的問題。
Let
let就是新的 var,和var不一樣的是它是塊級的,將上面的代碼中的var換成let
function checkStatus(status) { if (status) { let statusLabel = 'ok'; console.log(statusLabel); } else { console.log(statusLabel); } } checkStatus(true); checkStatus(false);
這樣的到的結果就是咱們設想的,true的時候是ok, false的時候拋出變量不存在的錯誤,若是false的時候想要輸出undefined, 那麼就要手動定義在 if 的上面:
function checkStatus(status) { let statusLabel; if (status) { statusLabel = 'ok' console.log(statusLabel); } else { console.log(statusLabel); } } checkStatus(true); checkStatus(false);
const
const 和 let 同樣是塊級, 從名字上看是用來常量的,其實否則,正確的說法是 single-assignment, 也就是說只能對其進行一次賦值而且只能在定義的時候賦值,後面若是再想對其進行賦值操做就會報錯。
const PI = 3.1415926; PI = 2.0; //報錯,Uncaught TypeError: Assignment to constant variable.
可是,這不表明const定義的就不能夠改變的(immutable), 以下代碼:
const animals = ['rabbit', 'monkey']; console.log(animals); //['rabbit', 'monkey'] animals.push('donkey'); console.log(animals);//['rabbit', 'monkey', 'donkey'] animals = ['bird']; //報錯,Uncaught TypeError: Assignment to constant variable.
那如何決定該使用哪一種關鍵詞呢?
這個目前社區沒有統一的規範,不過本人比較喜歡下面這種,即:
優先使用let
常量用const, 如常規常量, 導入的模塊等等。
全局變量使用var (基本上能夠不用了?)