As we know Execution Context (EC) consist of
- Varaiable Enviornment
- Scope Chain
- this keyword
So lets explore this keyword more.
- "this" keyword/variable in JS.
this is special variable that is created for every Execution Context (EC) i.e for every function.
this takes value of (or points to) the owner of the function in whcih the "this" keyword is used.
Remember "this" is not static it depends on how the function is called, and it's value is only assigned when the function is actually called.
As we know the function can be called in 4 different ways
a. method => this = <object that is calling the method>
- Ex:
Call to the function moreshwar.calcAge();
Note: The value of _*this *_should / is moreshwar
As we can say now that this is object giving call to method.
So, using this we can now access the properties of an object. Accessing the properties using (this) is a way better solution.
b. Simple function call: where this = undefined
Note: its is valid only for strict mode
Ex.
If not strict mode this will point to Global object / Windows object. Which can then be more problamatic.
This is reason we should always be useing strict mode.
c. Function call using Arrow function
i.e ArrowFunctionName => = <this of sorounding function (lexical this)>
In Arrow function it does not get the "this keyword".
d.
EventListner => this = <DOM elements that handler is attachedto>
Hence, this will never points to the function, where we are using it, it would point to the object (parent object).
Also "this" keyword will never point to the variable enviornment of the function.
"this" keyword in Global Scope is always Windows Object, which make this keyword dynamic not static.
Top comments (0)