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.
- 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
- When it's called in a function bound to an event handler,
thisis tied to that which is being listened too. Such as a button, an input, a form
create an object and give it some properties, also give it a function and use this.property to access one of the properties.
-
Set a property at the global level in the browser or node
this.color = 'red'; -
Access the global this with a function
function showThis() { console.log(this) } -
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()
- Try running this in node. you can output the getSkills() function with
thisis a useful bit of syntax if you know how to use it.- When using functions in the
methodsproperty, you can access data() variables withthiskeyword - Create small examples to get the hang of
this