본문 바로가기
공부낙서장

의식의 흐름대로 this공부

by 곰인간 2023. 4. 20.

filter메서드를 공부 중에 뜬금없이 this로 의식의 흐름이...


1차 적으로 this는 정규 함수식 내부에서만 동작하는가?

라고 갑자기 생각이 들었고,

아니라면 화살표 함수에서는 어떻게 동작하는가?

라고 생각이 들었다.

(아니 이전에 공부했다고 정리했었는데..)


this는 객체를 가리키는 위한 식별자이므로, 

그 대상이 함수가 될 수 없다.

일반 함수에서 사용 되는 함수 내부의 this는 전역객체인 window를 가리킨다.

const person = {
    name: 'A',
    sayHello() {
      setTimeout(function() {
        console.log(`Hello, my name is ${this.name}`);
      }, 1000);
    }
  };
  
  person.sayHello();
  
  // 결과값
  // Hello, my name is

위 코드에서 this는 전역객체인 window를 가리키고,

거기에 따른 결과의 출력값은 

Hello, my name is 

가 된다.

어..? 근데 undefined가 아니네?

name이라는 속성 대신에 다른 걸로 변경 시켜보자.

const person = {
    me: 'A',
    sayHello() {
      setTimeout(function() {
        console.log(`Hello, my name is ${this.me}`);
      }, 1000);
    }
  };
  
  person.sayHello();
  
  // 결과값
  // Hello, my name is undefined

name속성 대신에 me라는 속성을 사용하니깐

undefined가 출력된다.

이유인 즉슨,

 this는 전역객체인 window를 가리키는데,

위 코드대로 this.name은 결국 window.name이 된다.

window의 인스턴스 속성을 보면 name이 있는데,

window.name = ''이렇게 출력이 되므로 name속성을 사용하면

undefined가 아닌 빈 문자열이 출력된다.


위 예제의 this가 person이라는 객체를 가리키려면,

bind메서드를 써서 지정해주거나,

화살표 함수를 사용하면 간단하게 해결이 된다.

화살표 함수의 경우 상위에 존재하는 this에 바인딩 되는 성질이 있다.

const person = {
  name: 'A',
  sayHello() {
    setTimeout(() => {
      console.log(`Hello, my name is ${this.name}`);
    }, 1000);
  }
};

person.sayHello(); 

// 결과값
// Hello, my name is A

화살표 함수를 사용한 예제이다.

보시다시피 출력값에는 name속성의 값인 A가 등장.

setTimeout 안의 화살표 함수는 bind가 되어서 person이라는 객체를 가리킨다는 말씀?

const person = {
    name: 'A',
    sayHello() {
      setTimeout(function() {
        console.log(`Hello, my name is ${this.name}`);
      }.bind(this), 1000);
    }
  };
  
  person.sayHello();
  
  // 결과값
  // Hello, my name is A

bind를 사용해도 된다는 말씀!

댓글