this keyword/variable: is a special variable that is created for every execution context and therefore any function.
this keyword => will always take the value of the owner of the function in which, this keyword is used.We also say that it points to the owner of that function.
the value of the this keyword is not static. So it's not always the same. It depends on how the function is actually called. And its value is only assigned when the function is actually called.
let's analyze four different ways in which functions can be called.
1. Method: this = <Object that is calling the method>
So as a function attached to an object. So when we call a method, the this keyword inside that method will simply point to the object on which the method is called.(it points to the object that is calling the method).
const aniket = {
year: 1997,
calcAge: function () {
console.log(this);
console.log(2037 - this.year);
},
};
jonas.calcAge();
2. simply calling function as normal functions: this = undefined
So not as a method and so not attached to any object. In this case, the this keyword, will simply be undefined.However, that is only valid for strict mode. So if you're not in strict mode, this will actually point to the global object,which in case of the browser is the window object. And that can be very problematic.
3. Arrow functions this = <this of surrounding function
arrow functions do not get their own 'this keyword'. Instead, if you use 'the this variable' in an arrow function,it will simply be the this keyword of the surrounding function. So of the parent function. and in technical terms, this is called the 'lexical this keyword,' because it simply gets picked up from the outer lexical scope of the arrow function.
4. Event listener this = <DOM element that the handler is attached to>
if a function is called as an event listener, then the this keyword will always point to the DOM element that the handler function is attached to.
case-1. if the this keyword is outside of any function (just outside in global scope)
e.g.
console.log(this);
// Window object {...}
case-2. If the lexical scope (parent scope) of arrow function is global scope
e.g.
const age = birthYear => {console.log(birthYear);console.log(this);}age(1997);
// 1997
// Window object {...}
case-3. In case of regular function if you are not using strict mode
e.g.
const age = function (birthYear) {console.log(birthYear);console.log(this);};age(1997);
// 1997
// Window object {...}