'this' keyword
## 'this' keyword
In javascript, when a function is invoked
an 'execution context' is created for the function
each 'execution context' has a 'variable environment' where the variables declared inside the function live
the 'execution context' has a reference to its 'outer environment'
if the function code uses a variable which is not declared inside the function, then it can look for it in its 'outer environment'. If that 'outer environment' is another parent function and doesn't have the variable, the code can look for the variable further next level of outer environment until it reaches the global environment.
Every time javascript creates an 'execution context', it automatically creates a variable called 'this'.
'this' could be pointing to different objects depending on how the function has been invoked.
When used in global scope,
this
points towindow
objectWhen used inside a function statement or expression defined in global scope,
this
points towindow
objectWhen used in a function defined inside an object -
this
points to the objectWhen used in a function - nested inside a function which is defined inside an object -
this
points towindow
object. This is little weird. As a workaround for this, many developers define another variable usually namedthat
orself
in the parent function and assign it tothis
. Then usethat
/self
in the nested function instead ofthis
.When a function is invoked with the
new
keyword,this
would be a new empty object and passed on the function. Once function completes,this
would be returned.When called with
call()
,apply()
orbind()
, we can determine whatthis
in the function should point to, the first parameter passed in these function is whatthis
would point to.ES6's
Arrow
function, => Arrow function doesn't create its own this variable. When this is used in an arrow function, it points to it's parent's scope.
Last updated