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.
this
refers to an object when it’s into the object method.this
refers to the global object when it’s alone.this
with strict mode, its “undefined”this
refers to the element as this when receiving the event.this
refers 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.
Usethis
in 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/window
object.
Usethis
in “Strict” Mode.
'use strict'
console.log(this) <em>//widnow object</em>
function myFunction() {
return this
}
console.log(myFunction()) <em>//undefined</em>
In Strict mode whenthis
assign in global scope, it will refer to the global object.
But when its assign in function with strict mode, it willundefined
.
This
with 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.
This
withcall()
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 person1this
working 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.