JavaScript

JavaScript - this

인어공쭈 2024. 9. 2. 17:46

과제를 하던중 .bind(this)를 사용하게 되었는데 곰곰히 생각해보니깐 정확한 뜻을 알고 쓴게 아니라 습관적으로 해당 함수를 참조한다 라고만 생각하고 썻던거 같다.

 

그래서 이번에 디테일하게 개념부터 알아보려고 한다.

 

JavaScript에서 this 키워드는 함수를 호출 할때 결정된다. 함수를 어떤 방식으로 호출하는지에 따라 값이 달라진다는 것이다.

 

 

1. 전역 문맥 (Global Context)

전역 문맥에서 this는 전역 객체를 참조합니다:

  • 브라우저 환경에서는 전역 객체가 window입니다.
  • Node.js 환경에서는 전역 객체가 global입니다.
console.log(this); // 브라우저에서는 window 객체를 출력

 

 

2. 함수 문맥 (Function Context)

기본 함수에서 this는 호출 방식에 따라 달라집니다:

  • 전역 함수: 기본 함수에서 this는 전역 객체를 참조합니다.
function myFunction() {
  console.log(this); // 브라우저에서는 window, strict mode에서는 undefined
}

myFunction();

 

3. 생성자 함수 (Constructor Function) 문맥

생성자 함수에서 this는 새로 생성된 객체를 참조합니다. new 키워드를 사용해 생성자 함수를 호출할 때, this는 해당 새 객체를 가리킵니다.

function Person(name) {
  this.name = name;
}

const alice = new Person("Alice");
console.log(alice.name); // "Alice"

 

4. 이벤트 핸들러 문맥

이벤트 핸들러 함수에서 this는 이벤트를 처리하는 DOM 요소를 참조합니다.

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

 

 

5. bind, call, apply를 통한 this 변경

bind, call, apply 메서드를 사용해 this의 값을 명시적으로 설정할 수 있습니다.

  • bind: 새로운 함수를 생성하고 this를 고정시킵니다.
const obj = { name: "Alice" };
function greet() {
  console.log(this.name);
}

const greetAlice = greet.bind(obj);
greetAlice(); // "Alice"

 

 

6. 화살표 함수 (Arrow Function) 문맥

화살표 함수는 고유한 this를 가지지 않으며, 정의될 때의 상위 문맥의 this를 그대로 사용합니다. 이를 **lexical this**라고 합니다.

 

const obj = {
  name: "Alice",
  greet: function() {
    const innerGreet = () => {
      console.log(this.name);
    };
    innerGreet(); // "Alice"
  }
};

obj.greet();

 

반응형