Img Credit : sydney Rae
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
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.
this
in Global Scope or in function alone
Use If you run this code, you will see both of them are referring to the global/window
object.
this
in “Strict” Mode.
Use In Strict mode when this
assign in global scope, it will refer to the global object.
But when its assign in function with strict mode, it will undefined
.
This
with event handler
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
with call()
function
In this example, we can see in person1 this
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 to call()
. if you are clear with this example, hope you will try these function yourself.