> Articles > this keyword In JavaScript
this keyword in JavaScript is very useful and used heavily. In this article we will explain this keyword in JavaScript.
When the function is invoked it will have this. The value of this depends on how function is called. It can not be set by assigning any value like in other languages.
Let's see some examples of this keyword in JavaScript-
Context is global then this will point to Window object.
(1)this is inside the function and function is called then this will point to Window object.
(1)this is inside function and function is assigned to variable. If the function is called using variable then this will point to Window object.
this is inside function and function is inside object literal. If the function is invoked using object then this will point to object.
(1)this is inside function and function is inside object literal. If the function is invoked using object then this will point to object. But inside object if function is assigned to variable and called using that variable then it will point to Window object.
(1)Problem of this inside function of object literal pointing to Window object can be addressed by having one self variable. The value of this can be assigned to self variable at the start of function and then self can be used further instead of this.