RZ-Huang
    • 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
    # Scope 作用域 ###### tags: `javascript`、`concept` 每個變數會依據其生存範圍,也就是作用域來呈現最後的結果。 ``` var a = 20 function test() { var a = 10 console.log(a) // 10 } test() console.log(a) // 20 ``` 上面的例子,`var a = 20` 是一個全域變數,`var a = 10` 是在 function 為`test`的作用域當中設置的變數,因此在 `test` 函式裡面的 `console.log(a)` 會先在 `test`函式尋找有沒有符合的 `a` 變數,如果沒有,接著才會去尋找更外面的作用域是否有`a`變數,因此 `test()` 回傳的結果是`var a = 10` 設置的`10`。而第二個`console.log(a)`的結果為全域變數 `var a = 20` 設置的 `20`。 ``` var a = 20 function test() { a = 10 console.log(a) // 10 } test() console.log(a) // 10 ``` 上面的例子只是把原本的`var a = 10` 的`var`拿掉,只剩下`a = 10`,也就是說 `a` 沒有被重新宣告,所以說當`test()`呼叫函式的時候,因為在`test`當中沒有看到 `a` 被宣告,因此會往上找`a`有沒有被宣告,發現全域變數有宣告過了,因此把那個全域變數`a`的值改成`10`,所以之後拿取`a`的值都會是`10`。 ### 作用域鍊(scope chain) 試問以下三個 `console.log()` 答案為何。 ``` var a = 'global' function test(){ var a = 'test scope a' var b = 'test scope b' console.log(a, b) function inner() { var b = 'inner scope b' console.log(a, b) } inner() } test() console.log(a) ``` 1. test scope a test scope b 2. test scope a inner scope b 3. global 在 `inner` 這個 function 當中,因為它的作用域當中本身沒有 `a`,因此它往上一層作用域找,找到 `var a = 'test scope a'`所定義的 `a`,因此採用它,而 `b` 變數在它的作用域當中本身就有了,所以直接使用自身的`b`。 假如把`var a = 'test scope a'`這個去掉: ``` var a = 'global' function test(){ var b = 'test scope b' console.log(a, b) function inner() { var b = 'inner scope b' console.log(a, b) } inner() } test() console.log(a) ``` `inner` 的 `a` 值一樣先從自身作用域找,沒找到,因此尋找 `test` 的作用域,也沒有找到,所以繼續往上一層找,也就是全域變數的作用域,找到了,所以使用`global` 作為`a`的值。 而這一連串的找法就像一個作用域鍊一樣:inner scope -> test scope-> global scope。都是先從自身的 scope 開始找起,假如找不到就繼續往接著上一層的 scpoe 尋找,直到找到值為止。 ``` var a = 'global' function change(){ var a = 'change' function inner() { var a = 'inner' test() } inner() } function test() { console.log(a) } change() ``` 這個例子的`console.log(a)`結果會是 `global`,也就是全域變數`a`的值,因為 test scope chain 實際上是: test scope -> global scope,所以`test`在自身那一層沒找到的話就會跑去尋找 global scope 的那一層。換句話說,scope chain 並不會根據你在哪邊呼叫它而有所變化,而是在定義這個 scope 的時候它所處在的程式碼位置即已定案。 ### ES6 以後的作用域差別 ``` function test() { var a = 60 if (a === 60) { var b = 10 } console.log(b) } test() ``` 上面這個例子的變數宣告一樣是使用`var`,**對於`var`來說,它的作用域範圍以 function 為主**,所以在 function 裡面且在 `if` block 裡面的`b`變數其實在`test`當中都抓得到資料。 而,**從 ES6 開始加入了`let`與`const`兩個變數宣告型式,它們的作用域是以 block 為主**,也就是`{ }`大括弧,因此像上面的例子如果改成這樣: ``` function test() { var a = 60 if (a === 60) { let b = 10 } console.log(b) } test() ``` 結果會回傳`b is not defined` ,因為 `if` block 裡面的`let`變數在外面的作用域其實抓不到。

    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