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
    • 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 Versions and GitHub Sync Note Insights 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # <font class="h2">拉升(hoisting)</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> <br> :::danger 一但變數是使用var宣告,就要小心hoisting 變數宣告一律都放在函式內最前面,可避免 Hoisting 問題。 ::: :::info hoisting 是指「==一種把宣告提升到其所區域內最頂端==」的內部行為,不過提升行為指僅僅只針對宣告的部分,對於變數值的設定,並沒有跟著被提升。 ::: ==在宣告一個變數或函式之前,就能夠讓這個變數能先被使用,而不會出錯==。javaScript最特別的地方就是在你要使用一個變數之前,不一定要先宣告,只要在相同環境底下的其他地方有宣告,就不會發生錯誤。在許多常見的其他語言如果不先宣告,通常這時候都會出錯。 <br> ![](https://i.imgur.com/PLkNZVq.png =380x) **全域執行環境會做幾件事** - 創造全域環境(全域物件) - 創造this變數,並指向全域物件 - 進行記憶體指派的流程 記憶體指派就是了解提升(hoisting)的關鍵 :arrow_right:[執行環境execution contexts與執行堆疊execution stack](https://hackmd.io/@grayshine/S1wsLhXLY) <br> ### <font class="h3">執行環境分兩階段:1.創造環境、2.執行</font> ![](https://i.imgur.com/WMFrr9c.jpg =300x) <br> ### <font class="h4">記憶體是一對的</font> ![](https://i.imgur.com/Eoc4iHs.jpg =400x) <br> ### <font class="h4">➤ 1.創造環境(此時為拉升)</font> 創造環境時會將程式碼的==變數全部挑出來==,並放上key記憶體空間 這時還不會給它任何值,此時為`undefined` ![](https://i.imgur.com/0LE8HdM.jpg =350x) :::info 在這個階段,所有宣告的變數及函式都==只有做保留記憶體空間的動作,還沒被賦予值==,這個創造許多變數的階段,因此也被稱作「創造階段」。 在「創造階段」所做的,==為變數及函式保留記憶體空間的動作,就被稱為「提升」(Hoisting)==,因為這記憶體的保留,會讓程式碼看起來很像是將變數往上提了,所以才能夠在變數宣告前被取用而不會出現錯誤,不過實際上程式並沒有真的被移動。 ::: <br> ### <font class="h4">➤ 2.執行</font> 2. 到執行階段才依序賦予它們的值 ![](https://i.imgur.com/uPZGXrQ.jpg =330x) <br> :::info var可以拉升 例: ```javascript console.log(a); //會先給空值undefined var a = 1;//1 ``` ::: <br> ### <font class="h3">let 、const 的提升</font> let 、 const 宣告變數雖然還是有提升的作用,但是還是不能像 var 那樣自由的使用,等於有跟沒有一樣。 ```javascript function hello(){ consoel.log('hello'+name);//這段無法取用的區間稱為暫時性死區 (TDZ) let name ='Jack' } hello() ``` `const`、`let`宣告的變數一樣會先被保留記憶體位置,但關鍵差別,它們不像`var`那樣會先被指派預設值`undefined`,在進入執行階段,變數正式被指派之前,這個變數是不允許被使用的。既然在正式被指派之前不能被使用,那麼在同一區塊內,正式指派之前,就會有一個變數看似已經存在,卻無法使用的區間,這個尷尬區間被稱為「暫時性死區」Temporal Dead Zone(TDZ) <br> ### <font class="h3">函式</font> 除了宣告變數會保留記憶體空間(並給定預設值`undefined`),函式陳述式(具名函式)也會做一樣的事情,差別是整段函式內容會被完整的存入記憶體空間內。 :::info ```javascript var a = '1'; function fn(){} ``` **創造階段:** ```javascript function fn(){} var a ``` ![](https://i.imgur.com/9uCydS5.jpg =250x) **執行階段:** ```javascript a = '1'; ``` ![](https://i.imgur.com/WshgCJV.jpg =250x) ::: <br> :arrow_right:[何謂表達式(Expression)與陳述式(Statement)?](https://hackmd.io/@grayshine/SJYXEg2BF) ### <font class="h4">➤函式陳述式(具名函式)</font> ```javascript callName(); function callName(){ console.log('呼叫小名'); } //這樣執行結果會得到'呼叫小名' ``` 若是函式陳述式(具名函式),會將整個函式內容存入記憶體空間,因此==在宣告函式的區塊之前呼叫該函式是允許的==。 ==陳述式會優先被升,再來提升var變數== :::info 函式陳述式會被拉升 ![](https://i.imgur.com/1ACzsqm.jpg) ::: <br> ### <font class="h4">➤函式表達式(匿名函式)</font> ```javascript callName(); var callName = function(){ console.log('呼叫小明'); }//會報錯,callName is not a function ``` :::info 創造環境階段,變數會被拉升出來, ![](https://i.imgur.com/TtMz7cy.jpg) ::: <br> 範例1.-函式陳述式與函式表達式混和運用: ```javascript function callName(){ console.log('呼叫小明1'); } var callName = function(){ console.log('呼叫小明2'); } callName();//呼叫小明2 ``` :::info 函式陳述式與函式表達式上下作替換 ```javascript var callName = function(){ console.log('呼叫小明2'); } function callName(){ console.log('呼叫小明1'); } callName();//呼叫小明2 ``` 函式會優先被拉升,再來是變數 ![](https://i.imgur.com/ATEaHb5.jpg) ::: <br> 範例2. ```javascript callName(); function callName(){ console.log(Ming); } var Ming = '小明' //undefined ``` :::info 此時callName()未被定義值,所以結果會是undefined ![](https://i.imgur.com/mEadjvw.jpg) ::: <br> 範例3. ```javascript function callName(){ console.log('小明') } callName(); function callName(){ console.log('杰倫') } callName(); //杰倫 //杰倫 ``` :::info ![](https://i.imgur.com/06waHiD.jpg) ::: 範例4. ```javascript whosName() function whosName(){ if (name){ name = '杰倫'; } } var name = '小明'; console.log(name);//小明 ``` :::info ![](https://i.imgur.com/4U6U9DQ.jpg) ::: <br><br><br><br> ### <font class="h3">範例</font> ```javascript var x = 5; (function() { console.log(x); //undefined var x = 10; })(); console.log(x); ``` #### 程式實際執行過程 `var x`被提升了 ```javascript var x = 5; (function() { var x; console.log(x); //undefined x = 10; })(); console.log(x); ```

    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