2.1.1 var、let、const
var
let
const
var
是屬於 函式作用域(function scope)
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);
這樣的用法,很容易造成 區域變數
覆蓋 全域變數
的問題。
let
是屬於 區域作用域
const
是屬於 區域作用域
用來定義 常數(constant)
,只要宣告完以後就不能再更動了。
Last updated
Was this helpful?