--- title: 區塊 slug: Web/JavaScript/Reference/Statements/block translation_of: Web/JavaScript/Reference/Statements/block ---
{{jsSidebar("Statements")}}
區塊陳述用來組合零個或多個陳述。我們使用一對大括號 { } 以界定區塊。
陳述句 | |
Implemented in | JavaScript 1.0 |
ECMAScript edition | ECMA-262 1st edition |
{ 陳述_1 陳述_2 ... 陳述_n }
陳述_1
, 陳述_2
, 陳述_n
區塊陳述通常配合流程控制陳述(如 if
、for
、while
)一併使用。
var
使用var
區塊中定義的變數,其存取範圍是整個整個函式或是腳本,即為Execution Context的範圍中。
var x = 1; { var x = 2; } alert(x); // outputs 2
輸出結果是 2。因為var是宣告於整個腳本範圍中。
let
和 const
當使用let
或是const
進行宣告時,其存取範圍是只有本身定義的區塊中。
let x = 1; { let x = 2; } console.log(x); // logs 1
function
當function被呼叫時,會建立此function的Execution Context,因此在function區塊使用var
整個function區塊中都可對其進行存取。
function foo() { { var a = 'var'; { let a = 'let'; console.log(a); // let } } console.log(a); // var } foo();