자바스크립트 - this

코드위의승부사·2019년 11월 27일
0

JavaScript

목록 보기
1/8
post-thumbnail

this란?

The Object that is executing the current function

매번 달라지는 this

어떻게 함수를 호출했느냐(execution context)에 따라 this가 달라진다.

  • method -> obj
const video = {
  play() {
  console.log(this) -> `video Obj`
  }
  • function -> global(window, global)
function video(){
  console.log(this) -> `window`
}

callback function

const video = {
	title: 'a', 
	tags: ['a','b','c'],
	showTags(){
		this.tags.forEach(function(tag) {
        console.log(this, tag) -> `window`
        }); // }, this)
    }
};
video.showTags();
  • constructor mode
function Video(title){
	this.title = title;
	console.log(this); -> `Video`
}
const v = new Video('a') -> new 키워드가 생성한 빈 객체를 this가 가르킨다

Binding Problem

위의 콜백함수에서 가르키는 this가 기존의 객체가 아니라 윈도우를 가르키는 문제점이 발생한다. 이러한 문제의 해결책은 다음과 같다.

  • second parameter에 this 전달
const video = {
	title: 'a', 
	tags: ['a','b','c'],
	showTags(){
		this.tags.forEach(function(tag) {
        console.log(this, tag)  
        }, this); 
    }
};
video.showTags();
  • bind 함수 활용
const video = {
	title: 'a', 
	tags: ['a','b','c'],
	showTags(){
		this.tags.forEach(function(tag) {
        console.log(this, tag)
        }.bind(this));
    }
};
video.showTags();
  • arrow function 활용
const video = {
	title: 'a', 
	tags: ['a','b','c'],
	showTags(){
		this.tags.forEach((tag) => {
        console.log(this, tag)
        });
    }
};
video.showTags();

Reference

profile
함께 성장하는 개발자가 되고 싶습니다.

0개의 댓글