본문 바로가기
Programming/JavaScript

자바스크립트에서 this란?

by 성동구불주먹 2025. 4. 11.

🔍 this란?

자바스크립트에서 "누가" 실행했는지를 가리키는 키워드다.

기본적으로는 window를 나타낸다.

 

 

 

웹을 켜고 콘솔창에서 this를 입력하면 window 관련정보가 출력된다.

 

 

예를 들어서

어떤 객체(Object) 안에서 함수를 실행하면, 그 함수 안의 this는 그 객체 자신을 가리킨다.

 

const student = {
  name: 'ashley',
  sayHello: function () {
    console.log(this.name + ' 안녕!');
  }
};

student.sayHello(); // 👉 "ashley 안녕!" (this는 student를 가리킴)

 

 

 


 

 

익명 함수에서 this  VS 화살표 함수에서 this

 

익명함수(function)

const person = {
  name: 'ashley',
  sayHello: function () {
    console.log(this.name + ' 안녕!'); 
  }
};

person.sayHello(); // 👉 "ashley 안녕!" (this는 person을 가리킴)

 

익명함수에서 this는 함수를 '누가' 실행했는지에 따라 달라진다.

따라서 person.sayHello니까 this는 person 객체가 된다.

 

다른 예제를 하나 더 보자.

const person = {
  name: 'ashley',
  sayHello: function () {
    console.log(this.name);
  }
};

const say = person.sayHello;
say(); // 👉 undefined (전역에서 실행되니까 this는 window)

 

위에서와 달리 say라는 변수를 선언하고 person.sayHello를 할당했음에도

해당 변수가 전역에서 선언 및 실행되었기 때문에

this는 window객체를 가르키게 된다.

 

 

 

화살표 함수(() => )

const person = {
  name: 'ashley',
  sayHello: () => {
    console.log(this.name + ' 안녕!');
  }
};

person.sayHello(); // 👉 "undefined 안녕!" (❗이상함!)

 

화살표 함수에서는 this가 바깥의 this를 그대로 가져온다.

즉, this의 기본은 window(브라우저 전체)이기 때문에

해당 코드에서 아무리 name을 찾아도 window.name 값은 없기 때문에 undefined가 출력된다.

 

 


 

 

[번외 편 1] setTimeout 안에서의 차이

 

const dog = {
  name: '초코',
  bark: function () {
    setTimeout(function () {
      console.log(this.name + ' 멍멍!');
    }, 1000);
  }
};

dog.bark(); // 👉 "undefined 멍멍!" (this는 window)

 

 

💡해결방법 1 : this를 따로 저장하는 방법

const dog = {
  name: '초코',
  bark: function () {
    const that = this;
    setTimeout(function () {
      console.log(this); //window 객체정보 출력됨
      console.log(that.name + ' 멍멍!');
    }, 1000);
  }
};

//👉 "초코 멍멍!"

 

콘솔에 this를 찍어보면

this는 여전히 window 객체지만,

that이라는 변수를 선언해서 dog라는 객체를 할당했기 때문에

that.name으로 접근하면 '초코'가 출력된다.

 

 

💡 해결방법 2 : 화살표 함수 사용

const dog = {
  name: '초코',
  bark: function () {
    setTimeout(() => {
      console.log(this.name + ' 멍멍!');
    }, 1000);
  }
};

dog.bark(); // 👉 "초코 멍멍!"

 

외부 스코프의 this를 물려받는 성질을 이용해서

원하는 객체에 dog.bark()와 같이 접근 가능하다.

 

 


 

 

[번외 편 2] strict mode에서의 this

 

"use strict" 모드를 켜면 실수방지를 위한 언어 그대로 '엄격한 모드'가 된다.

"use strict";

function sayHi() {
  console.log(this);
}

sayHi(); // 👉 undefined (strict 모드에서는 this가 자동으로 window가 아님!)

 

일반 모드에서 this는 window지만,

strict 모드에서 this는 undefined가 된다.

 

 


 

정리하자면,

 

익명함수(function)는 누가 불렀냐에 따라 this가 달라지고,

화살표함수(() => {})는 화살표 함수가 정의된 시점에 있는 바깥 this를 기억해서 계속 쓴다.

반응형