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">立即函式 IIFE</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> :::info 常被使用在只會執行一次的程式碼,例如初始化的動作,並且可將程式碼包起來,形成一個區域,避免與全域變數汙染。有以下兩種優點: - 全域變數減少:若重複宣告相同的全域變數則會被覆蓋,因為變數暴露在全域中很有可能會被其他地方的程式修改,因此可將變數放在立即函式裡面避免被異動。 - 全域變數區域化:把全域變數當做參數傳遞給立即函式,因為 ==JavaScript 在尋找變數時會優先查找區域變數,若找不到再去尋找上層或全域變數,所以在效率上可獲得微幅提升==。 - ==另外 JavaScript 進行壓縮時,並不會對全域變數進行重新命名,區域變數則會重新命名,達到減少檔案大小==。 ::: <br><br><br> ```javascript function(){ console.log('This will never run again') } ``` ![](https://i.imgur.com/WFoMKPQ.png) 這裡函式沒有名字會跳錯 ```javascript (function(){ console.log('This will never run again') }()) ``` 可以以小括號將函式包起來欺騙javascript這是一個表達式 <br><br><br> ### <font class="h3">將全域變數區域化</font> ==JavaScript 進行壓縮時,並不會對全域變數進行重新命名,區域變數則會重新命名,達到減少檔案大小==。 ### 傳入全域變數到立即函式內 ![](https://i.imgur.com/dck1nGi.png) <br><br><br><br> ### <font class="h3">優先查找</font> ```javascript (function(){ function Array() {}; console.log(new Array()); //這邊會優先使用前面定義的Array這裡不是內建的Array, })(); ``` <br><br><br><br> ### <font class="h3">立即函式可以減少「全域變數」的產生,同時也避免了變數名稱衝突的機會</font> ```javascript function aaa(){ console.log("someThing"); } aaa(); ``` 函式最重要的是我們定義一段函式之後,在其他地方可以呼叫它 :::info 立即函式就是我們可以不用在別的地方呼叫它也可以執行它 ```javascript (function aaa(){ console.log("someThing"); }());//someThing ``` 這裡就算沒有`aaa()`函式也能立刻被執行 <br><br> ```javascript (function (){ console.log("someThing"); }());//someThing ``` 立即函示大多情況下是不需要名稱的(匿名函式),也可以被執行 <br><br> ```javascript (function (){ console.log("someThing"); })();//someThing ``` 立即函示的小括號是可以被移到外面的 ::: ==早期立即函示可以拿來限制作用域,ES6多了let、const的宣告方式,所以可以用「大括號」來限制作用域== <br><br><br> ### <font class="h4">➤立即函式特點:</font> 1. 立刻執行 2. 無法再函式外被再次執行 :::info 立即函式就算是具名函示,也無法再函式外被再次執行 ```javascript (function aaa(){ console.log("someThing"); }()); console.log(aaa)//aaa is not defined ``` ::: <br> ### <font class="h3">立即函式常做的使用</font> ### <font class="h4">限制變數的作用域</font> ```javascript (function() { var Ming = '小明'; console.log(Ming); })(); console.log(Ming);//Ming is not defined ``` 變數作用域在函式內,Ming只能在立即函式內被取得 <br> ### <font class="h4">傳入值</font> ```javascript var whereMing = (function (where){ return where; })('台北'); console.log(whereMing);//台北 ``` 因為立即函式本身是個表達式,所以可以回傳值,return回傳值到外層,因此我們就可以宣告一個變數`whereMing`來接收這個值 <br> ### <font class="h4">傳遞變數</font> ```javascript var a = {}; (function(b){ b.person = '小明'; })(a) ;(function(c){ console.log(c.person); })(a)//小明 ``` 將前面的立即函式傳遞到後面的立即函式 前面的立即函式,將`a`物件傳入立即函式加入了屬性`person`其值為`小明` 第二段立即函式,將`a`物件傳入第二段立即函式,印出`person`屬性值為`小明` <br> :bulb:因此可以利用全域物件`window`來傳遞一些值,常運用在大型的框架上 Vue框架:這個方法可以確保Vue可以正確掛載到全域變數上面 ```javascript (function(globe){ globe.person = '小明'; })(window) ;(function(c){ console.log(person); })()//小明 ``` <br><br><br><br> ### <font class="h4">for迴圈+非同步使用立即函式</font> ```javascript for(var i = 0;i<5;i++){ window.setTimeout(function(){ console.log(i) },1000) } //5 5 5 5 5 ``` 對非同步程式設計有所瞭解的可能都知道setTimeout裡的callback會在event loop的佇列裡堆積,直到`i++`操作完成。所以打印出兩個2。而這裡需要注意的是var i變數。因為沒有任何函式封裝,所以i將成為全域性變數。 ### 也可以使用立即函式 ```javascript for (var i = 0; i < 5; i++) { (function(x) { window.setTimeout(function () { console.log(x) }, 1000) })(i) } //0 1 2 3 4 ``` <br> ### <font class="h3">立即函式前面加分號</font> 為避免程式碼合併時出錯(因為如果eslint選stand句尾不會加分號) ```javascript ;(()=>{ }) ``` <br><br><br><br> ### <font class="h3">Js冷知識 void</font> 無論void後面的值是什麼,它都會回傳undefined的結果,但要是後面加上一個IIFE,即使這個function是有名字的。 像這樣,雖然void的使用情境不多,但有些開發者會習慣在此類一次性呼叫的IIFE前面,加上void來增加程式碼的可讀性。 ```javascript void function saySomething (msg){ console.log(msg) }('Hello') //Hello ``` <br> ```javascript void function saySomething (msg){ console.log(msg) }('Hello') saySomething('Hi') //saySomething is not defined ``` 但是若你再嘗試去呼叫saySomething這個函式會報錯

    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