[JS] this

swim·2024년 8월 23일

this

함수를 호출한 객체를 가리키는 키워드 - 함수가 호출될 때 어떤 객체가 그 함수를 호출했는지에 따라 상대적으로 값이 변하게 됨

  • 웹브라우저에서 this가 사용될때 → 전역객체, window 객체 가진다
  • 메소드를 정의하기 위한 함수 안에서는 메소드를 호출한 객체 가리킨다
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객체 출력됨

	

Arrow function 에서 ..

  • 호출한 대상에 따라 상대적으로 변하는 게 아니라 Arrow function 이 선언되기 적전에 그때 유효한 this값과 똑같은 값을 갖고 동작하게 된다
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 보다는 일반 함수가 좀 더 권장 된다

0개의 댓글