- Published on
Understanding this keyword in Javascript
- Authors
- Name
- Rakesh Yadav
- @jsbugpost
this
keyword in javascript is one of the most important concept every javascript developer need to understand.
this
keyword? 🤔
What is
this
keyword is special variable which is created for every execution context. It is used to access the properties and methods of the object which is currently executing. Value ofthis
variable depends on many factors that we will discuss in this article.
this
keyword 🧐
Important points about 👉 this
variable is created for every execution context.
👉 this
is not static. It's value depends on how the function is called.
1. If function is method of an object
In this case this
variable refers to the object.
Example:
const person = { name: 'Rakesh', age: 25, sayMyName: function () { console.log(`Hello ${this.name}`) },}person.sayMyName() // Hello Rakesh
In above example, this
variable reffering to person object.
2. If function is a regular function
If we run javascript in strict mode, then value of this
variable will be undefined otherwise it will refers window
object.
// In strict mode'use strict'function printThis() { console.log(this)}printThis() // undefined
// In non-strict modefunction printThis() { console.log(this)}printThis() // window
In above example, value of this
variable is undefined in strict mode and window
object in non-strict mode.
3. If function is a arrow function
Arrow function doesn't have it own this
variable. It's value is same as that of the function where it is called.
// In strict mode'use strict'const printThis = () => { console.log(this)}printThis() // window
// In non-strict modeconst printThis = () => { console.log(this)}printThis() // window
In above example, value of this
variable reffering to the window
object in both strict mode and non-strict mode.
As printThis
function is a arrow function and it will not have it's own this
variable.
4. If function is event handler
In this case this
variable refers to the DOM element on which the event is attached to.
const button = document.querySelector('button')button.addEventListener('click', function () { console.log(this)})// <button>
In above example, value of this
variable reffering to the button
DOM element.