用 let、const 取代 var
ECMAScript:6
在 ES6 之前, Javascript 是沒有 區塊作用域(block scope) 的概念的,一般常使用的 var 宣告變數是屬於 函式作用域(function scope)。
以下範例是一個最基本的 var 用法,在 function 內可以操作宣告的變數,出了 function 範圍外以後就讀不到了。
function test() {
var str = 'Hello';
console.log(str);
}
// Hello
test();
// str is not defined
console.log(str);
但是, var 因為是 函式作用域 的關係,所以在判斷式的區塊不受影響。
if (true) {
var str = 'Hello';
}
// Hello
console.log(str);
這樣的用法,很容易造成 區域變數 覆蓋 全域變數 的問題。因此 Javascript 在 ES6 中新增了 let 與 const 這兩個宣告方式來取代 var,這兩種方式都是屬於 區塊作用域 。
let
在擁有好的開發習慣下,大部份狀況直接將 var 取代成 let 都是沒問題的。
如果將剛剛 var 的判斷式區塊範例改寫成 let,因為 區塊作用域 的關係,就會產生 str is not defined 的錯誤了。
if (true) {
let str = 'Hello';
}
// str is not defined
console.log(str);
const
const 用來定義 常數(constant) ,只要我們宣告完以後就不能再更動了。
const num = 123;
// Error
num = 124;
另外,const 比較值得注意的是關於 Array 和 Object 操作。
在 Javascript 中,陣列和物件的操作都是屬於 reference type ,當變數成立時,變數的內容是指向記憶體某一個位置的。換句話說,當我定義了一個陣列常數之後,如果再 push 新的資料進去是可以執行的,因為指標並沒有指向另一個記憶體位置。
範例
const arr = [1, 2];
arr.push(3);
// [1, 2, 3]
console.log(arr);
const obj = {name: 'Johnson'};
obj.url = 'https://blog.johnsonlu.org';
// { name: 'Johnson', url: 'https://blog.johnsonlu.org' }
console.log(obj);
如果重新 assign 資料的話,就是新的記憶體區段了,因此就會出現錯誤訊息。
const arr = [1, 2];
// Error
arr = [1, 2, 3];