this
- 일반적으로 사용되지 않음
- 주로 함수 내부에서 사용
- 객체의 메소드를 만들 때 중요한 역할을 함
- 자바스크립트에서 this는 함수를 호출한 객체를 가르키는 키워드
- 함수가 호출될 때 어떤 객체가 함수를 호출했는지에 따라 상대적으로 값이 변하는게 특징
- 브라우저 안에서 자바스크립트가 동작한다면 전역객체인 window객체가 this의 기본값
console.log(this); // window 객체 출력
const user = {
firstName = 'Tess',
lastName = 'Jang',
getFullName: function() {
return `${user.firstName} ${user.lastName}`;
}
};
console.log(user.getFullName()); // Tess Jang
- 다른 객체에도 함수를 이용하고 싶을 때 유용하게 사용
function getFullName() {
return `return ${this.firstName} ${this.lastName}`;
}
const user = {
firstName: 'Tess',
lastName: 'Jang'
getFullName: getFullName
};
const admin = {
firstName: 'Alex',
lastName: 'Kim',
getFullName: getFullName
};
console.log(user.getFullName()); // Tess Jang
console.log(admin.getFullName()); // Alex Kim
복습
console.log(this); // window객체 호출
function printThis() {
console.log(this);
}
printThis();
- 객체의 매소드로 호출이 되는 경우
함수를 호출한 객체가 this에 담기기 때문에 같은 함수를 호출했지만 console에는 각각 다른 객체에 호출됨
const myObj = {
content: 'myObj',
printThis: printThis
};
const otherObj = {
content: 'otherObj',
printThis: printThis
};
myObj.printThis(); // {content: "myObj", printThis: f}
otherObj.printThis(); // {content: "otherObj", printThis: f}
* 일반함수
- 호출한 대상에 따라 값이 상대적으로 변함
* Arrow 함수
- Arrow Function이 선언되기 직전에 유효한 this값과 똑같은 값을 가지고 동작
console.log(this); // window 객체
const printThis = () => {
console.log(this);
};
const myObj = {
content: 'myObj',
printThis: printThis
};
const otherObj = {
content: 'otherObj',
printThis: printThis
};
myObj.printThis(); // window 객체
otherObj.printThis(); // window 객체
= this를 사용할 때는 Arrow 함수보다 일반함수를 권장함
QUIZ 01
다음 중 코드를 실행했을 때 콘솔에 출력되는 결과로 올바른 것을 선택해주세요.
function printThisTitle() {
console.log(this.title);
}
const courseA = {
title: '프로그래밍 기초 in JavaScript',
printTitle: printThisTitle
};
const courseB = {
title: '컴퓨터 개론',
printTitle: courseA.printTitle
};
const courseC = {
title: '웹 퍼블리싱',
printTitle: courseB.printTitle
};
courseA.printTitle(); // 프로그래밍 기초 in JavaScript
courseB.printTitle(); // 컴퓨터 개론
courseC.printTitle(); // 웹 퍼블리싱'Codeit > JavaScript' 카테고리의 다른 글
| Spread 구문 (0) | 2024.08.09 |
|---|---|
| 조건을 다루는 표현식 (0) | 2024.08.09 |
| Arrow Function (0) | 2024.08.09 |
| Rest Parameter (0) | 2024.08.09 |
| Argument (2) | 2024.08.08 |