Emmacheng
    • 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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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
    • Make a copy
    • 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 Make a copy 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    ###### tags: `JavaScript 學習紀錄` # [JS] What is “this” in JavaScript? What does “this” refer to? ## Outline - Simple call (直接的調用) - As an object method (物件的調用) - Arrow Functions (箭頭函式的調用) - As a DOM event handler (DOM 物件調用) - Strict mode (嚴格模式調用) - `call`, `apply`, `bind` (強制綁定 `this` 的調用) - As a constructor (建構式調用) ## Simple call 如果直接調用函式,此函式的 this 會指向 window,以下兩個範例都是直接調用函式,所以都是指向 window #### Example 1: this refers to window object ```javascript= window.name = 'window'; function callName() { console.log('call:', this.name); } callName(); //window ``` #### Example 2: 在function內宣並調用, simple call -> window ```javascript= window.name = 'window'; function callName () { console.log('call:', this.name); // function 內的 function function callAgainName () { console.log('call again:', this.name); } callAgainName(); } callName(); //"call:" "window" //"call again:" "window" ``` 小結: ==無論在哪一層,純粹的調用方式 this 都會指向 window== ## As an object method 如果 function 是在物件下被called,那麼 this 則會指向此object,無論 function 是在哪裡宣告 #### Example 1 ```javascript= var age = 18; var person = { age: 28, displayAge: displayAge } function displayAge() { console.log(this.age); console.log(this); } displayAge(); // 18 //window person.displayAge(); // 28, //{age: 28, displayAge: ƒ}, 在物件下呼叫,this 則是該物件 ``` #### Example 2: 把object裡面的function指給一個變數, 但還是用simple call ```javascript= window.age = 18; var person = { age: 28, displayAge: function () { console.log(this.age); console.log(this); } } //物件內的 function指給一個變數 var callThisName = person.displayAge; callThisName(); // 18, window ``` #### Example 3: nested object ```javascript= window.age = 18; function displayAge() { console.log(this.age); console.log(this); } var person = { age: 28, displayAge: displayAge, nestedPerson: { age:40, displayAge: displayAge } } displayAge(); //18 //window person.displayAge(); //28, //{age: 28, displayAge: ƒ}. this refers to the person object person.nestedPerson.displayAge(); //40 //{age: 40, displayAge: ƒ}. this refers to the nestedPerson object ``` ## Arrow functions: they don’t have their “own” this - 依據語彙環境的父層區域(parent scope)來綁定。白話的說,arrow function **定義位置**(不是呼叫順序)的上一層 this 代表誰,arrow function 內的 this 就代表誰 ```javascript= var person = { age:28, displayAge:function() { const displayAge2 = () => { console.log(this.age); console.log(this); } displayAge2(); //arrow function->parent this } } person.displayAge(); //28, {age: 28, displayAge: ƒ} ``` ## As a DOM event handler - DOM 搭配 addEventListener 時,this 指的是觸發事件的元素。以下這段程式碼可以貼在任何網頁下的 Console,接下來點擊畫面上任何一區域,該區域則會加上紅線 #### Example 1: DOM + addEventListener, this 是 DOM boject ```javascript= const box = document.querySelector('.box') box.addEventListener('click', function(){ console.log(this); // 這裡的 this 是 DOM box }) ``` #### Example 2: DOM + addEventListener + arrow function, this 是 parent 的 this ```javascript= const box = document.querySelector('.box') box.addEventListener('click', function(){ console.log(this); // DOM box setTimeout(()=>{ console.log(this); // DOM box. arror function->parent this },500) }) ``` ## Strict mode: 讓simple call的 this 不再是全域 window, 需要給它this - 現在會建議寫 JavaScript 的時候加入 'use strict',這可以改正一些coding不良習慣,但也有可以因此導致專案無法運作,此時可以考慮將 'use strict' 加在函式內,避免影響過去的程式碼及相關套件 #### Example 1 ```javascript= window.age = 28; function displayAge() { 'use strict'; console.log('call:', this.age); } displayAge(); // Uncaught TypeError: Cannot read properties of undefined (reading 'age') ``` #### Example 2:給 strict mode 一個this, object調用 or 綁定都可以 ```javascript= window.age = 38; const person = { age :28, displayAge: function displayAge() { 'use strict'; console.log(this.age); }, } person.displayAge(); //28. object call->this is person obj person.displayAge.call({ age: 18 }); //18. 強制綁this ``` ## 強制綁定 this `call`, `bind`, `apply` 這三者都可以傳入新的 this 給予函式使用,使其作為 this 所指向的物件,三者僅是使用方法不同 #### `call` - **`fn.call(this, arg1, arg2..., argn)`** - 第一個參數:想要綁定的 this - 第二以後的參數:想要傳進目標函式的參數,如果目標函式中不需要參數則不要傳入即可 - 功能 - 執行 function - 明確指定 this Example 1: 強制綁定18,永遠的18歲! ```javascript= var age = 28; function callName() { console.log(this.age); } callName(); // 28 callName.call({age: 18}); // 18 ``` Example 2: 除了傳入給定 this 的參數之外還可以傳入其他argument ```javascript= var obj1 = { myName: 'obj 1', fn: function (message) { console.log(this.myName + ' ' + message); } } var obj2 = { myName: 'obj 2', } obj1.fn.call(obj2, 'Hello'); //obj 2 Hello ``` #### `apply` - **`fn.apply(this, [arg1, arg2..., argn])`** - 第一個參數:想要綁定的 this - 第二個參數:與`call`類似, 只是第二個參數是陣列而且必須是陣列 - 功能 - 同`call` ```javascript= var obj1 = { myName: 'obj 1', fn: function (message) { console.log(this.myName + ' ' + message); } } var obj2 = { myName: 'obj 2', } obj1.fn.call(obj2, ['Hello']); //obj 2 Hello ``` #### `bind` - **`fn.bind(this, arg1, arg2..., argn)`** - 第一個參數:想要綁定的this - 想要傳進目標函式的參數,如果目標函式中不需要參數則不要傳入即可 - 回傳:回傳包裹後的目標函式 - 功能 - 明確指定 this - 回傳一個包裹函式,當我們執行這個函式時,同時將arguments 一起帶進 Function 中 - 無論函數怎麼被調用,原始函數的 this 在新函數將永遠與 bind 的第一個參數綁定起來, 只能綁一次的概念 Example 1 ```javascript= function fn() { console.log(this.a); } var bfn = fn.bind({a: 'Mark'}); var b2fn = bfn.bind({a: 'Rose'}); fn(); // undefind, 全域沒有定義a bfn(); // Mark b2fn(); // Mark. bind 只能使用一次!就算再綁Rose也沒用 ``` Example 2: object call + `bind` ```javascript= function fn() { console.log(this.a); } var bfn = fn.bind({a: 'Mark'}); var b2fn = bfn.bind({a: 'Rose'}); var obj = {a: 'John', fn: fn, bfn: bfn, b2fn: b2fn}; obj.fn(), obj.bfn(), obj.b2fn(); // John, Mark, Mark. object調用在bind過後會被取代 ``` ## As a constructor 在建構式下會 new 一個新物件,此時的 this 會指向新的物件 ```javascript= function TeamConstructor () { this.men = 'jamie' } class TeamConstructor { constructor(man) { this.man = man; } } var myTeam = new TeamConstructor(); console.log(myTeam.men); //jamie ``` ## 整理 - Simple call: window - As an object method: object本身 - Arrow Functions: parent this - As a DOM event handler: DOM object - Strict mode: 給它的this - `call`, `apply`, `bind`: 強制綁進去的`this` - As a constructor: 建構式本身new object ## 總結 - ==Regular function: how is called ?== - ==Arrow function: where is definded ?== ## Reference [this: Simple call, Object method, DOM event handler, Constructor](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/this) [Regular function v.s Arrow function](https://www.youtube.com/watch?v=dWZIPIc3szg) [Strict mode](https://www.w3schools.com/js/js_strict.asp) [call, apply, bind](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Function/call)

    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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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