본문 바로가기

Programming/JavaScript

The this Keyword in Practice

 

console.log(this); // Window {window: Window, self: Window, document: document, name: '', location: Location, …}
const calcAge = function (birthYear) {
  console.log(2022 - birthYear); // 34
  console.log(this); // undefined
};
calcAge(1988);
const calcAgeArrow = birthYear => {
  console.log(2022 - birthYear); // 34
  console.log(this); // Window {window: Window, self: Window, document: document, name: '', location: Location, …}
};
calcAgeArrow(1988);

Q. 왜 this keyword가 Arrow function에서는 undefined가 아닌 Window로 출력될까?

the Arrow function does not get its own this keyword.

Instead, the arrow function simply uses the lexical this keyword.

=> parent scope에서의 this keyword를 사용한다.

여기서는 Window가 global scope에서의 this keyword임.

const sunny = {
  year: 1988,
  calcAge: function () {
    console.log(this);
    console.log(2022 - this.year); //34
  },
};
sunny.calcAge();

method borrowing

borrowed a method from one object to the other

so no need to duplicate it

const matilda = {
  year: 2017,
};

matilda.calcAge = sunny.calcAge;

const sunny = {
  year: 1988,
  calcAge: function () {
    console.log(this);
    console.log(2022 - this.year); // 5 = 2022 - 2017
  },
};
sunny.calcAge();

const matilda = {
  year: 2017,
};

matilda.calcAge = sunny.calcAge;
matilda.calcAge();

calcAge 메서드는 sunny 안에 있지만

calcAge를 부르는 object 주체가 matilda이므로

this keyword를 사용할 수 있는거임

 

그래서 function 자체는 가져다 쓰지만

this.year은 sunny.year가 아닌

matilda.year인 2017으로 계산한거다.

 

this keyword is not static but dynamic.
It depends on how the function is called.
const f = sunny.calcAge;
f();

this가 undefined이니

this.year도 마찬가지임

'Programming > JavaScript' 카테고리의 다른 글

Regular Functions vs. Arrow Functions  (0) 2022.11.21
The this Keyword  (0) 2022.11.21
Variable Environment: Hoisting and The TDZ  (0) 2022.11.20
Hoisting and The TDZ in Practice  (0) 2022.11.20
Scoping in Practice  (1) 2022.11.19