JS - 閉包

JS - 閉包

閉包

作用域

js使用函式作用域, 函式內部的宣告的變數, 物件等等都只存在於該函式內

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

function funcA () {
let x = 10;
let y = 5;

function funcB() {
let z = 18;
console.log("func B", x + y);
}
// 執行
funcB();
// 印出funcB內的變數
console.log("func A", z);
}

function funcC () {
console.log("func C", x + y);
}

funcA();
// func B, 15
// z is not defined

funcC(); // x is not defined

函式內部的函式可以向外層作用域尋找(例:funcB可以找到外層funcA中的x和y), 然而這個行為是單向的, 外層並不能向內尋找(例:外層的funcA找不到內層funcB的z), 另外, 同層作用域底下的兩個函式, 他們作用域也是各不相干的(例:funcC無法找到funcA中的x和y)

Closure

定義

  1. A closure is the local variables for a function - kept alive after the function has returned. (javascriptkit.com)

閉包是一個函式內的一個區域變數 - 在該函示執行完/回傳之後, 仍然存活而沒有被釋放掉, 仍可以被使用

  1. Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope. (Kyle Simpson)

當一個函式可以記憶並且取用它原本的作用域內的東西(lexical scope, 語彙範疇, 在此先理解為函式的作用域), 即使這個函式是在它原先的作用域之外被執行

  1. A closure is a function having access to the parent scope, even after the parent function has closed. (W3C Schools)
    若是一個函式能夠在它的父層作用域被釋放掉時, 仍能取用其父層作用域的東西時, 該函式就能被稱為一個閉包

總結: 若是一個函式在其原本的作用域之外被執行, 但仍能取用其原先作用域中的東西的話, 它就能被稱為是閉包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

function funcA () {
let x = 10;
let y = 5;

function funcB() {
console.log("func B", x + y);
}
// callback
setTimeout(funcB, 1000);
}

funcA();
// 一秒後...
// func B 15

reference

Demystifying JavaScript Closure

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×