梁群嘉
    • 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
    ###### tags: `JavaScript` `箭頭函式` `學習` {%hackmd BJrTq20hE %} # 甚麼是箭頭函式與箭頭函式this的指向差異 ## 1-1甚麼是箭頭函式? 箭頭函式是一種新的函是寫法,與一般函式的寫法不同,有可以縮寫的優點。 範例如下 ### 1-1-1一般函式 ```javascript= let arr = [1,2,3,4,5]; let newarr = arr.map(function(item){ return item*2 }); console.log(newarr);//[2,4,6,8,10] ``` ### 1-1-2箭頭函式 ```javascript= let arr = [1,2,3,4,5]; let newarr = arr.map((item)=>{ return item*2 }); console.log(newarr);//[2,4,6,8,10] ``` 可以發現把function移除,然後在()後加上=> ## 2-1箭頭函式的縮寫 如果函式的參數只有一個,參數()也可以省略。 加入沒有參數的話()或兩個含以上參數存在的話則()不可省略。 ```javascript= let arr = [1,2,3,4,5]; let newarr = arr.map(item=>{ return item*2 }); console.log(newarr);//[2,4,6,8,10] ``` ### 2-2箭頭函式的縮寫2 函式需要return值的時候{}也可以省略,但是要注意原本{}的內容要寫在同一行。 ```javascript= let arr = [1,2,3,4,5]; let newarr = arr.map(item=>item*2); console.log(newarr);//[2,4,6,8,10] ``` ## 3-1箭頭函式沒有自己的this 原函式寫法this的指向 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName (){ console.log(this.name+' this指向obj'); // 因為在callback function 內的this都指向全域。 setTimeout(function(){ console.log(this.name+' this指向window') }) }, } obj.callMyName();//Jack this指向obj window this指向window ``` 從上面的例子可以看到callMyName()是從obj內調用的所以this指向obj,而setTimeout這個callback function是一種simple call 可以想成setTimeout()是放在window裡所以setTimeout()的this會指向window。 ### 3-1-1 箭頭函式this的指向 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName (){ console.log(this.name+'1'); setTimeout(()=>{ console.log(this.name+'2') }) }, } obj.callMyName();//Jack1 Jack2 ``` 把setTimeout內的函是改寫為箭頭函式,因為箭頭函式沒有自己的this,所以在箭頭含式內的this會指向外層函式的作用域的this,外層函式為傳統函式所以this的指向與如何調用函是相關。 ### 3-1-3沒有外層函式的的箭頭函式的this指向全域 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName: ()=>{ console.log(this.name); }, } obj.callMyName();//window ``` 箭頭函式內的this會與外層函式的this指向相同,上面的範例中沒有外層函式,所以指向全域。 ### 3-1-4外層也是箭頭函式的this的指向全域 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName: ()=>{ console.log(this.name+'1'); setTimeout(()=>{ console.log(this.name+'2') }) }, } obj.callMyName();//window1 window2 ``` 因為setTimeout外層函數也是箭頭函式,所以this的指向看外層函式,又因為外層函式是箭頭函式且沒有更外層的函式所以所有的this都指向window。 ### 3-1-5確定this的指向-方法1 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName (){ let vm = this; setTimeout(function(){ console.log(vm.name) }) }, } obj.callMyName();//Jack ``` 在callback function同層宣告變數vm=this;改變this的指向 ### 3-1-5確定this的指向-方法2 ```javascript= var name ='window'; const obj = { name:'Jack', callMyName (){ setTimeout(()=>{ console.log(this.name) }) }, } obj.callMyName();//Jack ``` 使用箭頭函式沒有this,會與(外層函式)作用域的this指向相同的特性把setTimeout內的this指向obj。 ## 4-1 一般函式與箭頭函式其餘參數的差異 一般函式的其餘參數 ```javascript= function fn() { console.log(arguments) } fn(1, 2, 3, 4) //Arguments(4) [1, 2, 3, 4,] ``` 箭頭函式則是沒有其餘參數,會報錯。 ```javascript= const fn = () => { console.log(arguments) } fn(1, 2, 3, 4) // VM1730:2 Uncaught ReferenceError: arguments is not defined ``` ### 4-1-1 箭頭函式的其餘參數要怎麼寫? ```javascript= const fn = (par, ...pars) => { console.log(par) console.log('其餘參數',...pars) const value = Object.values(pars) console.log('取出其餘物件', value) } fn(1, 'a', 'b', 5, 6)// 1 '其餘參數' a b 5 6 // ['a', 'b', '5', '6'] ``` ## 5-1 箭頭函式與call()、apply()、bind()對於this的指向 原始函式 ```javascript= var name = '123' const obj = { name: 'Jack' } const fn1 = function(par1, par2) { console.log(this.name, par1, par2) } fn1.call(obj, 'May', 'John') // Jack May John ``` 箭頭函式 可以看到使用Call但試箭頭函式內的this是指向全域,原因是箭頭函式沒有外層函數,所以會指向全域。 ```javascript= var name = '123' const obj = { name: 'Jack' } const fn1 = (par1, par2) => { console.log(this.name, par1, par2) } fn1.call(obj, 'May', 'John') // 123 May John ``` 箭頭函式與一般函式放在一起看 ```javascript= var name = '123' const obj = { name: 'Jack', fn1: (par1, par2) => { console.log('fn1',this.name, par1, par2) }, fn2:function(par1, par2) { console.log('fn2',this.name, par1, par2) }, fn3:function(par1, par2) { setTimeout(()=>{ console.log('fn3',this.name, par1, par2) }) }, fn4:(par1, par2) => { setTimeout(()=>{ console.log('fn4',this.name, par1, par2) }) } } //雖然call有定義this指向但是在箭頭函式內的this的指向還是由外層函數的this指向為主,如果沒有外層函式則指向全域。 obj.fn1.call(obj, 'May', 'John') // 123 May John obj.fn2.call(obj, 'May', 'John') // Jack May John obj.fn3.call(obj, 'May', 'John') // Jack May John obj.fn4.call(obj, 'May', 'John') // 123 May John ``` [箭頭函式、call this的指向 範例](https://codepen.io/efzdamnp-the-lessful/pen/VwXQyvp?editors=0011) ## 6-1 箭頭函式沒有建構函式 簡單的來說箭頭函式沒辦法透過.prototype增加方法 一般函式 ```javascript= const List = function(name){ this.name = name } const List2 = (name)=> { this.name = name } console.log(List.prototype, List2.prototype) //{constructor: ƒ} undefined const list = new List('Jack') console.log(list) // List {name: 'Jack'} const list2 = new List2('Jack') // Uncaught TypeError: List2 is not a constructor ```

    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