this가 가리키는 것

2024. 4. 11. 14:43·Javascript

자바스크립트에서의 this는 객체를 가리키는 키워드며, 어떻게(누가) 호출하는지에 따라 결정됩니다.

자세히 말하면, this는 호출한 주체입니다.

 

*아래 예제들은 ‘use strict’를 사용하지 않을 경우를 다룹니다.

호출 주체에 따른 this

호출주체: 전역스코프

console.log(this); // {...window}

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

// printThis를 호출한 것은 Window이므로 Window 객체를 출력합니다.
printThis(); // {...window}

 

호출주체: Object

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

const object = {
	printThis1: printThis,
	functions: {
		printThis2: printThis,
	}
}

// printThis1을 호출한 것은 'object'이므로 object 객체가 this 입니다.
object.printThis1(); // {printThis1: f, functions: {...}}

// printThis2를 호출한 것은 'functions'이므로 functions 객체가 this 입니다.
object.functions.printThis2(); // {printThis2: f}

 

호출주체: Event Listener

let btn = document.querySelector('button');
btn.addEventListener('click', function() {
	// 이벤트리스너의 'button'이 호출했으므로 this는 button입니다.
	console.log(this); // <button>...</button>(=== e.currentTarget)
	const arr = [1, 2, 3];
	arr.forEach(function(a){
		// 콜백함수는 이벤트리스너에서 호출하는 것이 아니므로 window를 가리킵니다.
		console.log(this); // {...window}
	}
	arr.forEach(() => {
		// arrow function은 this값을 window로 재설정 하지 않고 그대로 상위 this값을 사용합니다.
		console.log(this); // <button>...</button>(=== e.currentTarget)
	})
})

 

호출주체: 생성자

function human() {
	// this로 인스턴스를 생성합니다.
	this.arm = 2;
	this.leg = 2;
}
// new 사용 시 this를 리턴합니다.
const me = new human();
console.log(me); // human {arm: 2, leg: 2, constructor: Object}

 

호출주체 지정하기(call, bind)

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

const object = {
	data: 'Kim',
	functions: {
		printThis: printThis,
	}
}

const printer = object.functions.printThis;
// printer를 호출한 것은 'window'이므로 window 객체가 this 입니다. 
printer(); // {...window}

const bindedPrint = printer.bind(object);
// bindedPrint를 호출한 것은 'window'지만, object를 this로 고정했으므로 this는 object입니다.
bindedPrinter(); // {data: 'Kim', functions: {...}}
// bind와 달리 즉시 호출한다.
printer.call(object) // {data: 'Kim', functions: {...}}

 

 

 

 

 

 

 

 

 

 

[참고자료]

this 키워드를 알아보자 1. 함수와 Object에서 사용하면?

this 키워드를 알아보자 2. event listener와 constructor

자바스크립트 this란 무엇인가? | 웹 개발 입문자들을 위한 this 강좌!

저작자표시 비영리 변경금지 (새창열림)

'Javascript' 카테고리의 다른 글

모듈  (0) 2024.04.11
일급객체와 함수  (0) 2024.04.11
스코프와 클로저  (0) 2024.04.11
실행 컨텍스트: 호이스팅과 스코프 체이닝  (0) 2024.04.11
자바스크립트 엔진(Call Stack, Event Loop, …)  (0) 2024.04.11
'Javascript' 카테고리의 다른 글
  • 모듈
  • 일급객체와 함수
  • 스코프와 클로저
  • 실행 컨텍스트: 호이스팅과 스코프 체이닝
URE
URE
Skill: Javascript, ReactJS, Next.js, React Native ... *블로그 이전 작업(24. 04. 11 ~ 24. 04. 15)
  • URE
    Dev++
    URE
  • 전체
    오늘
    어제
    • 분류 전체보기 (51)
      • Browser (6)
      • OS (1)
      • Javascript (14)
      • React (19)
      • Next.js (4)
      • React Native (0)
      • Architecture (1)
      • Network (3)
      • 스크랩 (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    dataFetching
    참조타입
    swr
    JS
    TCP
    URL
    IP
    리액트
    javascript
    Port
    react
    Redux
    브라우저
    원시타입
    react18
    react concurrent
    자바스크립트
    리액트 코어
    상태관리라이브러리
    리덕스
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
URE
this가 가리키는 것
상단으로

티스토리툴바