메서드 내부에서 this 키워드를 사용하면 객체에 접근할 수 있습니다.
점 앞의 this는 메서드를 호출할 때 사용된 객체를 나타냅니다.
const user = {
name: "Hyerin",
age: 50,
sayHi() {
// 'this'는 '현재 객체'를 나타냅니다.
console.log(this.name);
}
};
user.sayHi(); // Hyerin
화살표 함수는 일반 함수와는 달리 ‘고유한’ this를 가지지 않습니다. 화살표 함수에서 this를 참조하면, 화살표 함수가 아닌 ‘평범한’ 외부 함수에서 this 값을 가져옵니다.
아래 예시에서 함수 arrow()의 this는 외부 함수 user.sayHi()의 this가 됩니다.
const user = {
firstName: "Hyerin",
sayHi() {
const arrow = () => console.log(this.firstName);
arrow();
}
};
user.sayHi(); // Hyerin