JS - this

99·2024년 10월 27일

JS(자바스크립트)

목록 보기
3/11
post-thumbnail

JavaScript에서 this는 함수가 호출될 때 결정되는 객체를 참조하는 키워드 입니다.
상황에 따라 this가 가리키는 대상은 달라지며, 함수를 어떤 방식으로 호출하느냐에 따라 다르게 설정 됩니다.



1. 일반 함수 내에서의 this

일반 함수에서는 전역객체(window 또는 global)를 참조합니다.

function showThis(){
	console.log(this);
}

showThis(); // 브라우저에서는 'window, Node.js에서는 'global' 객체 출력


2. 메서드 내에서의 this

객체의 메서드에서 this는 메서드를 소유한 객체를 참조합니다.

const person = {
	name : 'Joon',
    greet : function(){
    	console.log(this.name); // 'this'는 person 객체를 참조
    }
};

person.greet(); // 'Joon' 출력


3. 생성자 함수 내에서의 this

생성자 함수 내에서 this는 새로 생성된 인스턴스 객체를 참조합니다.

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

const joon = new Person('Joon');
console.log(joon.name); // 'Joon'출력


4. 화살표 함수에서의 this

화살표 함수는 this를 고정합니다. 따라서 화살표 함수 내부의 this는 상위 스코프의 this와 동일합니다.

const person = {
	name : 'Joon',
    greet : () => {
    	console.log(this.name); // 'this'는 상위 스코프의 'this'를 참조
    }
};

person.greet(); // undefined 출력(전역 객체에는 name이 없음)


5. call, apply, bind 메서드를 사용한 this 설정

JavaScript에서는 call(), apply(), bind() 메서드를 통해 this를 명시적으로 지정할 수 있습니다.

  • call() : 함수를 호출하면서 첫 번째 인자로 this를 설정합니다.
  • apply() : call()과 유사하지만, 인자를 배열 형태로 전달합니다.
  • bind() : 새로운 함수를 반환하면서 this를 영구적으로 설정합니다.
function greet(){
	console.log('Hello, ${this.name}');
}

const person = {name : 'Joon'};

greet.call(person); // 'Hello, Joon'
greet.apply(person); // 'Hello, Joon'

const greetPerson = greet.bind(person);
greetPerson(); // 'Hello, Joon'


6. 이벤트 핸드러에서의 this

이벤트 핸들러에서 this는 이벤트가 발생한 요소를 참조합니다.

<button id="myButton">Click me</button>

<script>
	const button = document.getElementById('myButton');
    button.addEventListener('click', function(){
    	console.log(this); // 클릭한 버튼 요소
    });
</script>

결과(콘솔창)

<button id="myButton">Click me</button> // 요소 전체가 출력됨.


마무리

this 요약

  • 전역 컨텍스트 : 전역 객체(window 또는 global).
  • 객체 메서드 : 메서드를 호출한 객체.
  • 생성자 함수 : 새로 생성된 인스턴스.
  • 화살표 함수 : 상위 스코프의 this를 유지.
  • 이벤트 핸들러 : 이벤트가 발생한 요소.

this는 상황에 따라 다르게 해석되므로, 특히 화살표 함수와 일반 함수의 차이점을 이해하고 사용 해야 합니다.

profile
99

0개의 댓글