The Object that is executing the current function
어떻게 함수를 호출했느냐(execution context)에 따라 this가 달라진다.
const video = {
play() {
console.log(this) -> `video Obj`
}
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();
function Video(title){
this.title = title;
console.log(this); -> `Video`
}
const v = new Video('a') -> new 키워드가 생성한 빈 객체를 this가 가르킨다
위의 콜백함수에서 가르키는 this가 기존의 객체가 아니라 윈도우를 가르키는 문제점이 발생한다. 이러한 문제의 해결책은 다음과 같다.
const video = {
title: 'a',
tags: ['a','b','c'],
showTags(){
this.tags.forEach(function(tag) {
console.log(this, tag)
}, this);
}
};
video.showTags();
const video = {
title: 'a',
tags: ['a','b','c'],
showTags(){
this.tags.forEach(function(tag) {
console.log(this, tag)
}.bind(this));
}
};
video.showTags();
const video = {
title: 'a',
tags: ['a','b','c'],
showTags(){
this.tags.forEach((tag) => {
console.log(this, tag)
});
}
};
video.showTags();