일반함수와 arrowfunction의 this는 가르키는 것이 다르다.
const person = {
firstName :'Viggo',
lastName :'Mortensen',
fullName : function(){
//여기서의 this는 person{}를 가르킴
console.log(this);
/*
{
firstName: 'Viggo',
lastName: 'Mortensen',
fullName: [Function: fullName],
fullName2: [Function: fullName2]
}
*/
return `${this.firstName} ${this.lastName}`
},
fullName2 :()=>{
//arrow function의 this는 window를 가르킴
console.log(this); // window
/*
[object Window]
*/
return `${this.firstName} ${this.lastName}`
}
}
//일반함수 메소드인 경우에는 this키워드가 왼쪽에 있는 객체를 가르킴
console.log(person.fullName()); //Viggo Mortensen
//arrowfunction 메소드인 경우에는
console.log(person.fullName2()); //undefined undefined
더 깊게 들어가지 말고 지금은 객체에서 메소드를 만들 때
arrow function을 사용하지 말고 일반함수로 메소드를 만들기로 합시다.