[JS] 자바스크립트에서 this

­Valentine·2021년 9월 16일
0

CS

목록 보기
2/23

this란?

this 바인딩이란 말 그대로 this를 고정하기 위해 사용된다. 이를 살펴보기 위해서는 우선 javascript에서 this가 어떻게 사용되는지 알아야 한다. 다음 예제를 보자.

let user = {
  job: "Student"

  toDo() {
    return this.job;
  }

};

console.log(`I am ${user.toDO()}`);

위의 예제는 I am Student를 출력할 것이다. this를 통해 toDo 메서드 내부에서 user 객체에 접근했기 때문이다. this를 사용하지 않고 다음과 같이 객체에 접근하는 것도 가능하다.

let user = {
  job: "Student"

  toDo() {
    return user.job;
  }

};

console.log(`I am ${user.toDO()}`);

앞서 살펴봤듯이 this는 소속된 객체를 참조하는 데에 사용된다. 또한 this는 호출된 객체를 참조하는 데에도 사용되는데 예시는 다음과 같다.

let user1 = { job: "Student" };
let user2 = { job: "Teacher" };

function toDo() {
  return this.job;
}

user1.f = toDo;
user2.f = toDo;

console.log(`I am ${user1.f()}`); // I am Student  (this == user1)
console.log(`I am ${user2.f()}`); // I am Teacher  (this == user2)

여기까지는 다른 언어와 비슷하나 javascript만의 특징이 있다. 객체 밖에서 this를 선언하면 window나 global가 할당된다는 점이다. 다음 예시와 함께 살펴보자

let user = {
  job: "Student",
  toDo() {
    console.log(`I am ${this.job}!`);
  }
};

setTimeout(user.toDo, 1000); // I am undefined!

위의 예제는 왜 Student가 아닌 undefined를 출력할까? 위의 코드는 다음과 같기 때문이다.

let user = {
  job: "Student",
  toDo() {
    console.log(`I am ${this.job}!`);
  }
};
let f = user.toDo;
setTimeout(f, 1000);

객체 메서드가 실제 메서드가 호출되는 곳(setTimeout 스케줄러)으로 전달되었다. 따라서, this에는 window가 할당되었으며, window 객체엔 job이 없으므로 undefined이 출력되었다.

레퍼런스

MDN-this
함수 바인딩
메서드와 this

profile
천체관측이 취미

0개의 댓글