6. this 함수

SUN·2022년 8월 26일

모던자바스크립트

목록 보기
6/8

1. about this

함수 밖에서의 this는 window 객체를 가져오지만 보통 함수 내부에서 주로 사용한다.

this는 호출한 객체를 가르킨다.

console.log(this);

function printThis() {
	console.log(this);
 }
 
 const myObj = {
 	content: 'myObj',
    printThis: printThis,
  }
  
const otherObj = {
	content: 'otherObj',
    printThis: printThis,
 }
 
 myObj.printThis();
 otherObj.printThis();
 
 
 // 첫 콘솔에는 window 객체가 나타나고
 두번째는 myObj, 세번째는 otherObj가 나타난다.

2. arrow 함수에서 this

일반 함수와 arrow 함수에서 this를 다루는 방식이 다르다

console.log(this);

const printThis = () => {
	console.log(this);
 }
 
 const myObj = {
 	content: 'myObj',
    printThis: printThis,
  }
  
const otherObj = {
	content: 'otherObj',
    printThis: printThis,
 }
 
 myObj.printThis();
 otherObj.printThis();
 
 
 // printThis를 arrow 함수로 바꾸면 모든 결과가 window로 바뀐다.
 arrow 함수 직전의 this 값이 window 객체

arrow 함수가 선언되기 직전의 값을 가지고 계속간다.

profile
안녕하세요!

0개의 댓글