| 語意 | 說明 | 範例 |
|---|---|---|
| 1. 區塊陳述式 | 組合多條陳述式,用於 if/else/for/while/try/catch/finally/function 等 |
if (x) { a(); b(); } |
| 2. 物件字面值 | 建立物件實例的表達式 | const obj = { name: 'Jack', age: 23 }; |
| 3. 函式主體 / 函式表達式主體 | 函式宣告或函式表達式的函式本體 | function f() { ... } / const f = function() { ... }; |
| 4. try/catch/finally 區塊 | 結構化例外處理的強制區塊(單行也不能省略大括號) | try { ... } catch(e) { ... } finally { ... } |
foo(); // OK:函式宣告會提升
function foo() { console.log('declared'); }
bar(); // TypeError: bar is not a function
var bar = function() { console.log('expressed'); };
{} 被誤判為區塊陳述式function(){}() // SyntaxError:解析為「函式宣告(缺名稱)+ 分組運算子」
{}.constructor // SyntaxError:解析為「空區塊」+ 存取屬性
[].constructor // OK:陣列字面值為表達式,無歧義
(function(){})() // IIFE:分組運算子包裹函式表達式
({}).constructor // 物件字面值表達式
[].constructor // 陣列字面值表達式(原本就合法)
// 變數接收也能強制表達式語境
const c = {}.constructor; // OK
const fn = function(){}(); // OK
JavaScript 解析器在「陳述式位置」看到 { 時,優先嘗試解析為 區塊陳述式(語意 1),而非物件字面值(語意 2)或函式表達式(語意 3)。
(function(){})() 或 void function(){}()。({a:1})。() => ({a:1}),否則大括號被視為函式本體。const {a, b} = obj; 此處大括號屬解構模式,非物件字面值。let/const{
let x = 1;
const y = 2;
var z = 3; // 函式作用域,非區塊作用域
}
console.log(z); // 3
// console.log(x); // ReferenceError
ES6 區塊陳述式配合 let/const 形成區塊級作用域,取代 IIFE 隔離變數的舊模式。
大括號虽小,語意豐富;搞清「所在位置決定語意」,即可避開 90% 的語法陷阱。