본문 바로가기
프론트엔드/JS 공부

자바스크립트 this

by 학습하는 청년 2025. 6. 4.

최종 수정: 2025.06.04

JavaScript의 This

함수가 호출될 떄 결정되는 특별한 키워드로, 현재 실행 컨텍스트에서 "누가 이 함수를 호출했는가"를 나타낸다. 이를 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수라고도 한다.


■ this 바인딩

바인딩 우선순위 (new - 명시적 - 암시적 - 기본)

1. 기본 바인딩 (Default Binding)

function sayHello() {
  console.log(this); // 전역 객체 (브라우저에서는 window)
}

sayHello(); // window 객체 출력

// strict mode에서는 undefined
"use strict";
function strictHello() {
  console.log(this); // undefined
}
strictHello();

 

2. 암시적 바인딩 (Implicit Binding)

const person = {
  name: "김철수",
  greet() {
    console.log(`안녕하세요, ${this.name}입니다.`); // this = person
  }
};

person.greet(); // "안녕하세요, 김철수입니다."

// 주의: 함수를 변수에 할당하면 this가 바뀜
const greetFunc = person.greet;
greetFunc(); // "안녕하세요, undefined입니다." (this = window)

 

3. 명시적 바인딩 (Explicit Binding)

function introduce() {
  console.log(`저는 ${this.name}이고, ${this.age}살입니다.`);
}

const person1 = { name: "김철수", age: 25 };
const person2 = { name: "이영희", age: 30 };

-- call --
introduce.call(person1); // this = person1
introduce.call(person2); // this = person2

// 인수도 전달 가능
function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}

greet.call(person1, "안녕하세요", "!"); // "안녕하세요, 김철수!"

-- apply --
// call과 비슷하지만 인수를 배열로 전달
greet.apply(person1, ["안녕하세요", "!"]); // "안녕하세요, 김철수!"

// 유용한 활용 예시
const numbers = [1, 5, 3, 9, 2];
const max = Math.max.apply(null, numbers); // Math.max(1, 5, 3, 9, 2)
console.log(max); // 9

-- bind 메서드 --
const person = {
  name: "김철수",
  greet() {
    console.log(`안녕하세요, ${this.name}입니다.`);
  }
};

// bind는 새로운 함수를 반환
const boundGreet = person.greet.bind(person);
boundGreet(); // "안녕하세요, 김철수입니다." (this가 영구적으로 person에 바인딩)

// 이벤트 핸들러에서 유용
button.addEventListener('click', person.greet.bind(person));

 

4. new 바인딩

function Person(name, age) {
  this.name = name;  // this = 새로 생성된 객체
  this.age = age;
  
  this.greet = function() {
    console.log(`안녕하세요, ${this.name}입니다.`);
  };
}

const person1 = new Person("김철수", 25); // this = 새 Person 인스턴스
person1.greet(); // "안녕하세요, 김철수입니다."

■ 화살표 함수의 this

화살표 함수는 자신만의 this를 갖지 않고, 상위 스코프의 this를 그대로 사용한다.

const person = {
  name: "김철수",
  
  // 일반 함수
  normalGreet() {
    console.log(`일반: ${this.name}`); // this = person
    
    function inner() {
      console.log(`내부: ${this.name}`); // this = window (undefined in strict)
    }
    inner();
  },
  
  // 화살표 함수
  arrowGreet() {
    console.log(`화살표: ${this.name}`); // this = person
    
    const inner = () => {
      console.log(`내부 화살표: ${this.name}`); // this = person (상위 스코프 상속)
    };
    inner();
  }
};

person.normalGreet();
// "일반: 김철수"
// "내부: undefined"

person.arrowGreet();
// "화살표: 김철수"  
// "내부 화살표: 김철수"

■ 이벤트 핸들러에서의 this

이벤트를 보낸 요소로 설정된다.

const button = document.querySelector('button');

// 1. 일반 함수 - this는 이벤트가 발생한 요소
button.addEventListener('click', function() {
  console.log(this); // button 요소
  this.style.backgroundColor = 'red';
});

// 2. 화살표 함수 - this는 상위 스코프
button.addEventListener('click', () => {
  console.log(this); // window 객체
});

// 3. 객체 메서드를 이벤트 핸들러로 사용
const handler = {
  color: 'blue',
  handleClick() {
    console.log(this.color); // 'blue'를 기대하지만...
  }
};

button.addEventListener('click', handler.handleClick); // this = button
button.addEventListener('click', handler.handleClick.bind(handler)); // this = handler

'프론트엔드 > JS 공부' 카테고리의 다른 글

클로저  (0) 2025.06.04
프로토타입 체인  (0) 2025.06.04
동기 / 비동기  (0) 2025.05.28
스토리지(Storage)  (0) 2024.05.01
쿠키(Cookie)  (0) 2024.05.01

댓글