본문 바로가기

Programming/JavaScript

The this Keyword

EXECUTION CONTEXT
- Variable environment
- Scope chain
- this keyword

- this keyword/variable: Special variable that is created for every execution context (every function). Takes the value of (points to) the "owner" of the function in which the this keyword is used.

- this is NOT static. It depends on how the function is called, and its value is only assigned when the function is actually called.

 

Method
this = <Object that is calling the method>
const sunny = {
  name: 'Sunny',
  year: 1988,
  calcAge: function () {
    return 2022 - this.year;
  }
};
sunny.calcAge();

calcAge is method

this -> sunny

this.year -> 1988 가리킴

Way better than using sunny.year!

 

Simple function call
this = undefined
-> In strict mode! Otherwise: window (in the browser)
Arrow functions
this = <this of surrounding function (lexical this)>
-> Arrow functions do not own this keyword ⭐️⭐️⭐️
Event listener
-> this = <DOM element that the handler is attached to>

 

this does NOT point to the function itself, and also NOT the its variable environment!