개발 공부 일지/JavaScript
자바스크립트 - this
yelimu
2024. 7. 19. 15:14
this: 함수를 호출한 객체를 가르킴
선언한 내용 없이 this 를 호출하면 window 객체가 출력됨
화살표 함수에서는 항상 window 가 출력됨(호출 이전에 유효한 객체 = window)
function getFullName(){
return `${this.first} ${this.last}`;
}
const user = {
first: 'Tess',
last: 'Jang',
getFullName: getFullName,
};
const admin = {
first: 'Alex',
last: 'Kim',
getFullName: getFullName,
};
console.log(user.getFullName()); -> this = user -> user 의 getFullName 속성에 접근 -> getFullName 함수 호출
console.log(admin.getFullName()); -> this = admin
this 를 활용한 메소드를 객체 내부에서 선언하고
다른 객체에서 그 메소드를 참조하더라도, this 는 항상 그 메소드를 호출한 객체를 가리킨다