[JS] This

조수현·2025년 7월 27일

서론

이번 주가 자바스크립트 개념 마지막이길 바라며!

this

this는 자바스크립트 키워드 중 하나로 자기 참조 변수

  • 상황에 따라 다른 값을 가르키므로 주의해야 함

상황별 this

this는 사용되는 상황에 따라 다른 객체를 가르킨다 같은 함수의 형태라도 용도에 따라 다른 객체를 가르키니 유의해야 함

전역

전역에서의 this는 전역 객체를 가르킴

console.log(this) // window
console.log(this === window)

일반 함수 this

function 키워드로 생성되며, 메서드가 아닌 함수에서는 전역 객체를 가르킴

  function foo() {
    console.log("function: ", this); // window
  }

foo();

생성자 함수 this

생성자 함수에서의 this는 생성될 인스턴스 객체를 가르킴
new 키워드가 없다면 전역 객체를 가르킴

  function Food(name, color) {
    this.name = name;
    this.color = color;
    console.log("constructor: ", this); 
  }

   const food1 = new Food("strawberry", "red"); // food1 가르킴
   const food2 = Food("banana", "yellow"); // window 가르킴

메서드 this

객체의 메서드에서 호출된 this는 객체를 가르킴

const obj = {
  name: "soo",
  age: 20,
  getName: function () {
    console.log("method: ", this); // obj를 가르킴
    return this.name
  },
};

obj.getName();

화살표 함수 this

화살표 함수로 생성된 this는 호출된 환경의 this를 따라감

  • 전역에서 실행되는 화살표 함수는 전역에서의 this와 같은 전역객체를 가르킨다
 const arrowFunction =()=> {
   console.log("arrow function: ",this)  // window
 }

  • this가 obj를 가르키는 getName에서 화살표 함수를 생성한다면 화살표 함수의 실행환경인 getName의 this를 따라 obj를 가르킨다
 const obj = {
   name: "soo",
   age: 20,
   getName: function () {
     console.log("method: ", this);

     const getAge = () => {
       console.log("arrow method: ", this);
     };
     getAge();

     return this.name
   },
 };

obj.getName();

개인적인 생각

  • 외우면 너무 좋지만 외워도 자주 사용하지 않으면 금방 잊히기 쉽다
  • 까먹었다면 이렇게 상황별로 다르다는 것을 인지하고 this 사용 시 어떤 값이 들어오는지 확인해 보면 충분할 것 같다

this 할당

this가 가르키는 값은 개발자가 의도적으로 할당이 가능하다

call

함수에 this를 할당하며 함수를 실행함

function.call(this에 할당할 값, 함수 인수1, 함수 인수2, ...)

apply

call과 같지만 인수를 배열로 전달

function.apply(this에 할당할 값, [함수 인수1, 함수 인수2, ...])

bind

call, bind와 다르게 함수를 반환함

const returnFunction = function.bind(this에 할당할 값)

returnFunction(함수 인수1, ...)
profile
프론트엔드 개발 블로그

0개의 댓글