-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
마지막 부분에 질문 있습니다.
22.06.30 23:08 작성 조회수 149
1
const user = {
name:"Mike",
showName: function(){
console.log(`hello, ${this.name}`);
},
};
let fn = user.showName;
// this가 지워진다. 왜??
// 왜 바로 fn()하면 this.name이 발동이 안되지?
// fn(); // error. Cannot read properties of undefined (reading 'name')
마지막 부분에 바로 fn();을 하면 this.name을 하지 못해 오류가 나는데, 왜 let fn으로 할당을 할 때 this가 지워지는 지 궁금합니다.
답변해주시면 감사하겠습니다.
답변을 작성해보세요.
0
ycc20182
질문자2022.07.01
let fn = user.showName; 으로 받게 되면
showName 이 가리키는 함수 functon()도 fn이 받게 됩니다.
그러면 이 function()함수 안에 있는 this.name에서 this는 fn 자체를 가리키게 됩니다. fn에는 name에 대한 정보가 없기 땜누에 typeerror가 발생합니다. 따라서, this를 user로 할당시켜 줘야하기 때문에 call, apply, bind가 활용됩니다.
답변 1