함수를 호출한 객체를 가리키는 키워드 - 함수가 호출될 때 어떤 객체가 그 함수를 호출했는지에 따라 상대적으로 값이 변하게 됨
function getFullName() {
return `${this.firstName} ${this.lastName}`;
}
const user = {
firstName: 'Tess',
lastName: 'Jang',
getFullName: getFullName,
};
const admin = {
firstName: 'Alex',
lastName: 'Kim',
getFullName: getFullName,
};
// getFullName 안에서의 this는 getFullName을 호출한 user객체가 담긴다!
console.log(user.getFullName()); //Tess Jang
console.log(admin.getFullName()); //Alex Kim
console.log(this); //window 객체 출력됨
function printThis() {
console.log(this);
}
const myObj = {
content: 'myObj',
printThis: printThis,
};
const otherObj = {
content = 'otherObj',
printThis: printThis;
};
myObj.printThis(); //myObj 객체 출력됨
otherObj.printThis(); //otherObj객체 출력됨
console.log(this); //window 객체 출력됨
function printThis = () => {
console.log(this);
}
const myObj = {
content: 'myObj',
printThis: printThis,
};
const otherObj = {
content = 'otherObj',
printThis: printThis;
};
myObj.printThis(); //window 객체 출력됨
otherObj.printThis(); //window 객체 출력됨
⇒ 그래서 객체를 만들때는 Arrow function 보다는 일반 함수가 좀 더 권장 된다