Closure 閉包


Posted by hoyi-23 on 2021-08-12

const name = "Ted";
function printName(){
    console.log(name)
}
printName() // Ted

上面是很平常就可以看到的程式碼,其實這一整個程式碼就是一個Closure 閉包


Closure 閉包。就是指我們可以取得函式外部的變數值的範圍(作用域)。
每個Scope都可以取得外層Scope的東西

  1. 這一整區塊就是一個 Scope
    const name = "Ted";
    function printName(){
     console.log(name)
    }
    printName() // Ted
    
  2. 這區塊也是一個 Scope
    function printName(){
     console.log(name)
    }
    

大部分的範例都會以包在函式內的函式來說明:

function outerFunction(outerVariable){
    return function innerFunction(innerVariable){
        console.log('Outer Variable:' + outerVariable)
        console.log('Inner Variable:' + innerVariable)
    }
}

const newFunction = outerFunction('outside')
newFunction('inside')

// Outer Variable: outside
// Inner Variable: inside

通常function內的變數,在沒被呼叫時,記憶體就會將它釋放。而閉包因為知道還會用到,所以就不會釋放。


#closure #閉包







Related Posts

[python] 關於python三兩事 - class,  __init__,   __call__

[python] 關於python三兩事 - class, __init__, __call__

匯入小工具 (2) - 如何與資料庫連接

匯入小工具 (2) - 如何與資料庫連接

筆記、advanced JS 整理

筆記、advanced JS 整理


Comments