const audio = {
tilt: "a",
play() {
console.log("play this", this);
},
};
audio.play();
//play this { tilt: 'a', play: [Function: play] }
audio.stop = function () {
console.log("stop this", this);
};
audio.stop();
//stop this { tilt: 'a', play: [Function: play], stop: [Function (anonymous)] }
function playAudio() {
console.log(this);
}
playAudio();
//Window {window: Window, self: Window, document: document, name: '', location: Location, …}
function Audio(title) {
this.title = title;
console.log(this);
}
const audio = new Audio("a");
//Audio {title: 'a'}
그 이외
const audio = {
title: "audio",
categories: ["rock", "pop", "hiphop"],
displayCategories() {
this.categories.forEach(function (category) {
console.log(`title: ${this.title}, category: ${category}`);
});
},
};
audio.displayCategories();
title:undefined가 나타남, 이유는 forEach 안의 this는 함수 내에 있기 때문에 window를 가르킴
해결 방법
const audio = {
title: "audio",
categories: ["rock", "pop", "hiphop"],
displayCategories() {
this.categories.forEach(function (category) {
console.log(`title: ${this.title}, category: ${category}`);
}, this);//forEach 두 번째 매개변수가 가르키는 것은 메소드의 this이
},
};
audio.displayCategories();
결과
title: audio, category: rock
title: audio, category: pop
title: audio, category: hiphop
forEach뒤에 this를 붙여 해결
forEach의 첫 번째 매개변수: 콜백 함수,
두 번째 매개변수: thisArg(콜백함수에서 this로 참조 가능하게함)
const audio = {
title: "audio",
categories: ["rock", "pop", "hiphop"],
displayCategories() {
this.categories.forEach((category) => {
console.log(`title: ${this.title}, category: ${category}`);
});
},
};
audio.displayCategories();
화살표 함수에서 this는 상위 스코프의 this를 가리키게 된다(Lexical this)
const fullName = function () {
console.log(`${this.firstName}${this.lastName}`);
};
const person = {
firstName: "Kim",
lastName: "HJ",
};
fullName.call(person);
//KimHJ
함수에서 this를 메소드를 가리키게 함
const fullName = function () {
console.log(`${this.firstName}${this.lastName}`);
};
const person = {
firstName: "Kim",
lastName: "HJ",
};
fullName.apply(person);
//KimHJ
function func(lan) {
if (lan === "kor") {
console.log(`lang:${this.kor}`);
} else {
console.log(`lang:${this.eng}`);
}
}
const greeting = {
kor: "안녕",
eng: "hello",
};
const boundfunc = func.bind(greeting);
boundfunc("kor");
//안녕
boundfunc("eng");
//hello