Skip to content

Instantly share code, notes, and snippets.

@ashx3s
Last active November 24, 2021 03:03
Show Gist options
  • Select an option

  • Save ashx3s/64a8cdd87a2ba916a8c537a2acf0b1e1 to your computer and use it in GitHub Desktop.

Select an option

Save ashx3s/64a8cdd87a2ba916a8c537a2acf0b1e1 to your computer and use it in GitHub Desktop.
Javascript => this

Javascript this

this is a javascript keyword that is used to reference the object that the function it is in belongs to. It can be used in global and function contexts.

  • Review the MDN article on this
    • For use in vue methods, pay particular attention to the As a DOM Event Handler section closer to the bottom of the article.

Basic Rules of how this works

  • It is determined by it's context
    • When declared inside of a function, the function is the context; when it is used outside of a function - it refers to the global context.
  • In the browser, the global context is the window
  • In node, the global context is globalThis

DOM Event Listener

  • When it's called in a function bound to an event handler, this is tied to that which is being listened too. Such as a button, an input, a form

This examples

create an object and give it some properties, also give it a function and use this.property to access one of the properties.

  1. Set a property at the global level in the browser or node

    this.color = 'red';
    
  2. Access the global this with a function

    function showThis() {
      console.log(this)
    }
    
  3. Make a method invokation

    let character = {
      name: 'Frodo',
      species: 'Hobbit',
      skills: [
        {
        melee: '14'
        },
        { 
        yellingSam: '9001'
        }
      ],
      getSkills: function () {
        return this.skills.forEach(skill => {
          for (let i in skill) {
            console.log(`${i}: ${skill[i]}`)
          }
        })
      }
    }
    
    • Try running this in node. you can output the getSkills() function with character.getSkills()

Notes

  • this is a useful bit of syntax if you know how to use it.
  • When using functions in the methods property, you can access data() variables with this keyword
  • Create small examples to get the hang of this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment