This is one of the most common questions in Javascript interviews. In general, the “this” keyword refers to an object depending on the situation and its uses.

  • thisrefers to an object when it’s into the object method.
  • thisrefers to the global object when it’s alone.
  • thiswith strict mode, its “undefined”
  • thisrefers to the element as this when receiving the event.
  • thisrefers to any object when use methods likecall(),apply()&bind()can refer

Use in Method

let Country = {
  name: 'Bangladesh',
  sayName: function () {
    console.log(this.name) <em>//Bangladesh</em>
  },
}
Country.sayName()

Copy the code and run,

You will see, that its prints the country name, which is the property of the Country object. That means in the method this will reference its object.

Usethisin Global Scope or in function alone

console.log(this) <em>//widnow object</em>
function getThis() {
  console.log(this) <em>//widnow object</em>
}
getThis()

If you run this code, you will see both of them are referring to the global/windowobject.

Usethisin “Strict” Mode.

'use strict'
console.log(this) <em>//widnow object</em>

function myFunction() {
  return this
}
console.log(myFunction()) <em>//undefined</em>

In Strict mode whenthisassign in global scope, it will refer to the global object.

But when its assign in function with strict mode, it willundefined.

Thiswith event handler

button onclick="this.style.display='none'">Click to Remove Me!</button>

Just run this code and click on button, it will remove as display none. that means when the event happening this is referring to itself.

Thiswithcall()function

const person1 = {
  fullName: function () {
    return this.firstName + ' ' + this.lastName
  },
}

const person2 = {
  firstName: 'John',
  lastName: 'Doe',
}

let x = person1.fullName.call(person2)
console.log(x) <em>//John Doe</em>

In this example, we can see in person1thisworking as persob2 object. cause when we call the fullname from person1 , we call person2 to as this. That’s why person is reffer to the this.

apply()&bind()are works also similar tocall(). if you are clear with this example, hope you will try these function yourself.