[JavaScript] this

Byeonghyeon·2025년 1월 30일

공부

목록 보기
16/21

this

this는 JavaScript에서 현재 실행 중인 컨텍스트(Context)를 참조하는 키워드로, 함수가 호출되는 방식에 따라 값이 달라진다.

전역 컨텍스트

전역 스코프에서 this전역 객체를 참조한다.

  • 브라우저 환경: window
  • Node.js 환경: global
console.log(this) // 브라우저 : window, Node.js: {}

객체 메서드에서의 this

const player = {
    name: "Stroud",
    getName: function () {
      return this.name;
    },
  };
  
  console.log(player.getName()); // "Stroud"

객체의 메서드 내부에서 this해당 메서드를 호출한 객체를 참조한다.

생성자 함수에서의 this

function Player(name) {
    this.name = name;
  }
  
  const stroud = new Player("Stroud");
  console.log(stroud.name); // "Stroud"

생성자 함수에서 this새로 생성된 객체를 참조한다.

클래스에서의 this

class Animal {
    constructor(type) {
      this.type = type;
    }
  
    getType() {
      return this.type;
    }
  }
  
  const cat = new Animal("Cat");
  console.log(cat.getType()); // "Cat"

클래스 내부의 this해당 인스턴스를 참조한다.

이벤트 핸들러에서의 this

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

기본적으로 this는 이벤트를 바인딩한 DOM 요소를 참조한다.

document.querySelector("button").addEventListener("click", () => {
  console.log(this); // 전역 객체 (window) 또는 undefined (strict mode)
});

하지만 화살표 함수를 사용하면 this는 상위 스코프를 따른다.

화살표 함수에서의 this

const obj = {
  name: "Arrow",
  getName: () => {
    console.log(this.name);
  },
};

obj.getName(); // undefined (전역 객체의 this를 참조)

화살표 함수는 자신만의 this를 가지지 않으며, 항상 상위 스코프의 this를 참조한다.

call, apply, bind

call, apply, bindthis 값을 명시적으로 설정하기 ㅇ ㅟ해 사용하는 메서드이다.

  1. call()

call은 함수를 즉시 호출하면서 첫 번째 인자로 this 값을 설정하고, 나머지 인자를 개별적으로 전달한다.

function greet(greeting, punctuation) {
    console.log(`${greeting}, ${this.name}${punctuation}`);
  }
  
  const person = { name: "Alice" };
  
  greet.call(person, "Hello", "!"); // Hello, Alice!
  1. apply()

apply는 함수를 즉시 호출하면서 첫 번째 인자로 this 값을 설정하고, 두 번째 인자로 인자를 배열로 전달한다.

function greet(greeting, punctuation) {
    console.log(`${greeting}, ${this.name}${punctuation}`);
  }
  
  const person = { name: "Alice" };
  
  greet.apply(person, ["Hi", "."]); // Hi, Alice.
  1. bind()

bind는 함수를 호출하지 않고, this가 고정된 새로운 함수를 반환한다.

function greet(greeting, punctuation) {
    console.log(`${greeting}, ${this.name}${punctuation}`);
  }
  
  const person = { name: "Alice" };
  

  const boundGreet = greet.bind(person, "Hey");
  boundGreet("?"); // Hey, Alice?

0개의 댓글