iT邦幫忙

2022 iThome 鐵人賽

DAY 16
0
自我挑戰組

I don't know JS yet系列 第 16

[ Day 16 ] I don't know JS yet - Closure

  • 分享至 

  • xImage
  •  

Closure is when a function remembers and continues to access variables from outside its scope, even when the function is executed in a different scope.

一個函式能夠 access 其 scope 以外的變數,就稱為 closure (閉包)。

    function greeting(msg) {
        return function who(name) {
            // the **who** function closes over the varaible *msg*,
            // which is the parameter from the outer scope
            console.log(`${ msg }, ${ name }`);
        }
    }
    
    // calling greeting(...) create an instance of the inner function,
    // and when the inner function is retured,
    // its reference is assigned
    // to the **hello** and **howdy** variable in the outer scope.

    var hello = greeting('Hello');
    var howdy = greeting('Howdy');
    
    hello('Janet');   // Hello, Janet
    hello('Alice');   // Hello, Alice
    howdy('Sarah');   // Howdy, Sarah
    
    // After finishing running these functions,
    // the msg didn't go away since closure.
    // Because the inner function instances are
    // still alive ( assigned to hello and howdy ),
    // their closures arer still preserving the msg variables.

再看一個例子,我覺得 closure 很像「雙心石滬」,variable 進得去出不來

    function counter(step) {
      var count = 0;
      console.log(`Outer scope count ${ count }`);
      return function increaseCount() {
        // this closure close over the count variable,
        // and it can actually observe or make updates to the count variable
        count += step;
        console.log(`Count: ${ count }`);
      }
    }

    var increase1 = counter(1); // Outer scope count 0
    var increase3 = counter(3); // Outer scope count 0

    increase1(); // Count: 1
    increase1(); // Count: 2

    increase3(); // Count: 3
    increase3(); // Count: 6
    increase3(); // Count: 9

每當執行 increase1() 或者 increase3() 都是在呼叫increaseCount,又因為 countstep 都被 close 了,所以它們的值會被 closure 保留、更新,closure 是 close variable 而不是其 value

[ 參考 ]
-https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/get-started/ch3.md#closure


上一篇
[ Day 15 ] I don't know JS yet - Iteration
下一篇
[ Day 17 ] I don't know JS yet - this
系列文
I don't know JS yet30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言