[Javascript] this

SNXWXH·2025년 3월 18일

Javascript

목록 보기
10/13
post-thumbnail

this

  • this는 실행 컨텍스트에 따라 다른 값을 가짐
  • this 바인딩은 함수가 호출되는 방식에 의해 결정

기본적인 this의 동작

  • 전역 컨텍스트
    • 브라우저 환경: window 객체
    • Node.js 환경: global 객체 또는 undefined (strict mode)
  • 함수 내부
    • 일반 함수 호출: 전역 객체 (window 또는 global)
    • strict mode ('use strict' 적용): undefined
function showThis() {
  console.log(this); // window (strict mode에서는 undefined)
}

showThis();

객체의 메서드에서 this

  • 객체의 메서드 내부에서 this는 해당 객체를 가리킴
const obj = {
  name: "JavaScript",
  showThis() {
    console.log(this); // obj
  }
};

obj.showThis();

생성자 함수에서 this

  • 생성자 함수 내부에서 this는 새로 생성되는 객체를 가리킴
function Person(name) {
  this.name = name;
}

const user = new Person("John");
console.log(user.name); // John

화살표 함수에서 this

  • 화살표 함수는 자신만의 this를 가지지 않고, 상위 스코프의 this를 상속
  • 화살표 함수는 bind(), call(), apply()로도 this를 변경할 수 없음
const obj = {
  name: "JavaScript",
  showThis: () => {
    console.log(this); // 전역 객체 (window 또는 global)
  }
};

obj.showThis();

this의 명시적 바인딩 (call, apply, bind)

  • call(), apply(), bind()를 사용하면 this를 특정 객체로 지정 가능
function greet() {
  console.log(this.name);
}

const user = { name: "Alice" };

greet.call(user); // Alice
greet.apply(user); // Alice

const boundGreet = greet.bind(user);
boundGreet(); // Alice

클래스에서의 this

  • 클래스의 메서드 내부에서 this는 해당 인스턴스를 가리킴
class Person {
  constructor(name) {
    this.name = name;
  }

  showThis() {
    console.log(this); // 인스턴스 객체
  }
}

const user = new Person("Bob");
user.showThis();
  • 클래스 메서드를 이벤트 핸들러로 사용하면 this가 바뀔 수 있으므로 bind()가 필요할 수 있음
class Counter {
  constructor() {
    this.count = 0;
  }

  increase() {
    console.log(this); // undefined (strict mode), 또는 이벤트 대상 객체
    this.count++;
  }
}

const counter = new Counter();
const button = document.querySelector("button");

// 바인딩하지 않으면 `this`가 변경될 수 있음
button.addEventListener("click", counter.increase.bind(counter));

this와 이벤트 리스너

  • 일반 함수로 이벤트 리스너를 등록하면 this는 이벤트를 발생시킨 DOM 요소를 가리킴
  • 화살표 함수로 이벤트 리스너를 등록하면 this는 상위 스코프의 this를 따름
const button = document.querySelector("button");

button.addEventListener("click", function () {
  console.log(this); // 클릭한 버튼 요소
});

button.addEventListener("click", () => {
  console.log(this); // 상위 스코프의 this (전역 객체)
});
호출 방식this가 가리키는 대상
전역 컨텍스트브라우저: window / Node.js: global (strict mode에서는 undefined)
일반 함수 호출window 또는 global (strict mode에서는 undefined)
객체의 메서드 호출해당 객체
생성자 함수 호출 (new 사용)새로 생성된 객체
화살표 함수상위 스코프의 this를 상속
profile
세상은 호락호락하지 않다. 괜찮다. 나도 호락호락하지 않으니까.

0개의 댓글