개발 도구 (Development Tools)/JavaScript

[JavaScript] 사용 위치에 따른 this의 변화

BiCute 2022. 5. 16. 10:00
반응형

 

#1 일반 함수에서 사용될 경우

function 디스(){
    console.log(this);
  }

디스();

this = Window

 

단, strict mode라면 undefined

'use strict'

function 디스(){
    console.log(this);
  }

디스();

 

 

#2 오브젝트 내에서 함수(Function)로 사용될 경우

let 오브젝트 = {
  이름: "후시딘",
  디스: function(){
    console.log(this)
  }
}
  
오브젝트.디스();

this = 속해있는 object

 

 

#3 오브젝트 내에서 화살표 함수(Arrow Function)로 사용될 경우

let 오브젝트 = {
  이름: "후시딘",
  디스: () => {
    console.log(this)
  }
}
  
오브젝트.디스();

this = 함수 바깥쪽의 this를 가져옴

 

 

#4 생성자(constructor)에서 사용될 경우

function 생성자() {
  this.이름 = "후시딘",
  this.나이 = 19
}

let 오브젝트 = new 생성자();

console.log(오브젝트);

this = 새롭게 생성되는 오브젝트(instance)

 

 

#5 EventListener에서 사용될 경우

// HTML
<div id="box">박스</div>

// JavaScript
document.getElementById('box').addEventListener('click', function(){
	console.log(this);
})

this = 지금 이벤트가 동작하는 지점

이 경우 e.currentTarget과 동일.

 

 

주의

오브젝트 내에서 다음과 같이 콜백 함수가 사용될 경우.

let 오브젝트 = {
  이름: ["후시딘", "라파엘"],
  디스: function(){
    오브젝트.이름.forEach(function(){
      console.log(this)
    })
  }
}  

오브젝트.디스();

this는 window가 되어버린다. 

오브젝트 안에 있지만 사용된 콜백 함수가 일반 함수이기 때문인데, 이런경우 화살표 함수(Arrow Function)를 이용하면 의도한 값을 유도할 수 있다.

let 오브젝트 = {
  이름: ["후시딘", "라파엘"],
  디스: function(){
    오브젝트.이름.forEach(() => {
      console.log(this)
    })
  }
}  

오브젝트.디스();

결과

 

 

 

반응형