grayshine
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # <font class="h2">閉包Closure</font> ###### tags: `javascript` <style> .h2 { background: linear-gradient(135deg,#fff,#537479) ; color: #537479; display:block; padding: 6px 5px; border-radius: 4px; } .h3 { background: linear-gradient(180deg,#fff 50%,#c9d5d4) ; color: #537479; display:block; padding: 6px 5px; border-bottom: 3px solid #537479; } .h4 { color: #537479; font-weight:bold; font-size:1.1em; } </style> ![](https://i.imgur.com/yOgZWY5.png) <br><br><br><br> 閉包是在==用一個函式去操作另一個函式,這個函式必須是巢狀的,並且去取用它外層函式的變數。== 正常函式內宣告的變數,會在函式執行完後無法再被取得。也就是說通常在一個函式內,沒辦法取得另一個函式內的變數。 <br> :::info 簡單的說就是呼叫函式內的函式,將記憶體封存在內層 最簡單的做法是將閉包視為「==保留的作用域==」,外層function的變數不會被記憶體回收掉。 閉包是包裝的或封閉的作用域,它在函式旁邊「隱形地」傳遞。 呼叫該函式時,它可以隱含地存取此閉包提供的作用域。 ::: <br> ```javascript function addAB(a){ return function addB(b){ console.log(a+b); }; } var addB = addAB(3); var result = addB(5); console.log(result);//8 ``` 對`addB`函式而言,在其內部有引用到它內部沒有的變數`a`,根據「範疇鍊」的規則,==它會轉為向外部的語彙環境尋找==,它會看到原來`a`變數在`addAB`函式就已經存在了,所以Javascript引擎就會為此保留這個函式的記憶體空間不會釋放,所以這個暫時存在的封閉環境,就被稱為「閉包」 ![](https://i.imgur.com/C380eEW.png) ![](https://i.imgur.com/mH95Ta6.jpg =600x) <br><br> ### <font class="h4">➤ 範例:</font> ```javascript function storeMoney(){ var money = 1000; return function(price){ money = money +price; return money; } } var MinMoney = storeMoney(); console.log(MinMoney(100));//1100 console.log(MinMoney(100));//1200 console.log(MinMoney(100));//1300 ``` money =1000會不斷地被取用,它的==記憶體就不會被釋放掉== <br><br><br><br> ### <font class="h4">➤ 範例二:</font> ```javascript var count = 0; function counter(){ return ++count; } console.log(counter()); //1 console.log(counter()); //2 console.log(counter()); //3 ``` ==當程式碼變多,過多的全域變數會造成不可預期的錯誤,這時改用閉包就可以避免這些問題== <br><br> ```javascript function counter(){ var count = 0; function innerCounter(){ return ++count; } return innerCounter; } const countFunc = counter(); console.log(countFunc()); //1 console.log(countFunc()); //2 console.log(countFunc()); //3 ``` 使用閉包 <br><br> ```javascript function counter(){ var count = 0; return function(){ return ++count; } } const countFunc = counter(); console.log(countFunc()); //1 console.log(countFunc()); //2 console.log(countFunc()); //3 ``` 簡化 <br><br><br><br> ### <font class="h4">➤ 範例二:</font> ```javascript function counter = () =>{ var count = 0; return () => ++count; } const countFunc = counter(); console.log(countFunc()); //1 console.log(countFunc()); //2 console.log(countFunc()); //3 ``` 箭頭函式再簡化 <br><br><br><br> ### <font class="h4">➤ 閉包與this範例</font> ```javascript var name = "A"; var obj = { name: "B", getName: function() { return function() { return this.name; }; } }; var result = obj.getName(); console.log(result()); //A ``` ```javascript var name = "A"; var obj = { name: "B", getName: function() { var that = this; //使用閉包 return function() { return that.name; }; } }; var result = obj.getName(); console.log(result()); //B ``` <br><br><br><br> ### <font class="h4">經典範例:</font> ```javascript function pushFuncToArray() { var funcArr = []; for (var i = 0; i < 3; i++) { funcArr.push(function () { console.log(i); }); } return funcArr; } var functionArr = pushFuncToArray(); functionArr[0]();//3 functionArr[1]();//3 functionArr[2]();//3 ``` javascript的確會暫時為你保留`i`的記憶體空間,不過在把函式推送到陣列裡面的時候,並沒有立即引用到`i`,所以等到`pushFuncToArray`結束,一個個執行`functionArr`裡面的的函式時,`i`早就已經因為for迴圈數值被修改為3,這時候怎麼拿都是3 <br> ```javascript function pushFuncToArray() { var funcArr = [] for (var i = 0; i < 3; i++) { (function (j) { funcArr.push(function () { console.log(j) }) })(i) } return funcArr } var functionArr = pushFuncToArray() functionArr[0]()//0 functionArr[1]()//1 functionArr[2]()//2 ``` 這裡如果使用「立即函式」就可以限制作用域,for迴圈內的函式就會立刻被執行,得到答案就會是0,1,2 <br><br> ```javascript function pushFuncToArray() { var funcArr = []; for (let i = 0; i < 3; i++) { funcArr.push(function () { console.log(i); }); } return funcArr; } var functionArr = pushFuncToArray(); functionArr[0]();//0 functionArr[1]();//1 functionArr[2]();//2 ``` 如果這邊for迴圈如果是使用`let`的話`i`的作用域就會限制在`{}`裡面,也會得到0,1,2 <br><br> ### <font class="h3">閉包的運用</font> ### <font class="h4">函式工廠</font> 函式工廠:可以依據傳入的變數來定義它的初始值 ```javascript function storeMoney(initValue) { var money = initValue || 1000; return function (price) { money = money + price; return money; } } var MingMoney = storeMoney(100); console.log(MingMoney(500)); //600 ``` `var money = initValue || 1000`這邊`||`優先性大於`=`,所以`||`會先執行 `initValue || 1000`,如果`initValue`是0這會執行右邊的1000,不然真值都會執行左邊。 這函式執行就像是工廠,給他不同的材料,它就可以生產出不同的結果,中間是透過函式去執行相同的動作,此稱作函式工廠 <br><br> ### <font class="h4">私有方法</font> ```javascript function storeMoney(initValue) { var money = initValue || 1000; return { increase: function (price) { money += price; }, decrease: function (price) { money -= price; }, value: function () { return money; } } } var MingMoney = storeMoney(100); MingMoney.increase(200); MingMoney.increase(25); console.log(MingMoney.value()); ``` 這樣就可以透過閉包來完成函式工廠與私有方法, 函式工廠:可以依據傳入的變數來定義它的初始值 私人方法:透過物件型式來對初始值做不同的操作(這邊回傳了一個物件) 這樣就可大幅增加函式的可用性,這也是閉包在實作中常用到的一些方法 <br><br><br><br> ### <font class="h3">閉包其他範例</font> ### <font class="h4">➤範例一</font> ```javascript let f const g = function () { const a = 23 f = function () { console.log(a * 2) } } g() //46 f() //undefined console.dir(f) //可以查看閉包 ``` ![](https://i.imgur.com/mpMUxO1.png) <br><br><br> ### <font class="h4">➤閉包有優先權範例</font> ![](https://i.imgur.com/RvnjE7X.png) ### 如果沒有閉包settimeout的函式會取用全域的變數(settime函式基本上是在全域執行的) ![](https://i.imgur.com/L9TVZsy.png) <br><br><br><br> ### <font class="h3">閉包與bind作預設值</font> ```javascript const addTax = (rate,value) =>value+value*rate const addVAT = addTax.bind(null,0.23) console.log(addVAT(100)) //123 console.log(addVAT(23)) //28.29 ``` ### 也可以使用閉包: ```javascript const addTax = function(rate){ return function(value){ return value + value*rate } } const addVAT = addTax(0.23) console.log(addVAT(100)) //123 console.log(addVAT(23)) //28.29 ``` <br><br><br><br> ### <font class="h3">setTimeout範例</font> 對非同步程式設計有所瞭解的可能都知道==setTimeout裡的callback會在event loop的佇列裡堆積,直到`i++`操作完成==。所以打印出兩個2。而這裡需要注意的是var i變數。因為沒有任何函式封裝,所以i將成為全域性變數。 ```javascript for(let i = 0;i<5;i++){ window.setTimeout(function(){ console.log(i) },i*1000) } //0 1 2 3 4 ``` 當var被修改成let時,情況發生了改變。程式執行結果是1~4。 首先需要認識到let和var在作用域上的差別。var被圈定在函式內,而let被圈定在任何有中括號的範圍內。雖然上圖的for迴圈沒有將i圈定在中括號內,但ES6仍然在此機制上給let設定了屬於自己的作用域。 <br><br> ### 也可以使用立即函式 這邊使用==閉包==的觀念,立即函式帶入了參數,會行程區塊作用域,i變數會被緩存 ```javascript for (var i = 0; i < 5; i++) { (function(i) { window.setTimeout(function () { console.log(i) }, i*1000) })(i) } //0 1 2 3 4 ``` <br><br> ### 也可以使用setTtimeout傳入第三個參數形成閉包 ```javascript for (var i = 0; i < 5; i++) { window.setTimeout(function (i) { console.log(i) }, i*1000,i) } //0 1 2 3 4 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully