728x90
This
일반 함수의 this는 호출 위치에서 정의
화살표 함수의 this는 자신이 선언된 함수 범위에서 정의
즉, 화살표 함수는 자신의 this를 가지고 있지 않고 자신을 감싸고 있는 일반 함수의 this를 가지게 된다.
- 일반함수
const user = {
firstName : 'Potter',
lastName : 'Harry',
age : 18,
getFullName : Function() {
return `${this.lastName} ${this.firstName}`
}
}
console.log(user.getFullname()) // Harry Potter
- 화살표 함수
function user() {
this.fisrtName : 'Leo'
this.lastName : 'D.'
return {
firstName : 'Potter',
lastName : 'Harry',
age : 18,
getFullName : () => {
return `${this.lastName} ${this.firstName}`
}
}
}
const u = user();
console.log(u.getFullname()) // D. Leo
해당 화살표 함수의 this 키워드는 현재 함수를 감싸고 있는 외부 함수를 참조함
728x90
'FE > Javascipt' 카테고리의 다른 글
[Javascipt] String (0) | 2023.07.20 |
---|---|
[Javacript] 클래스 (0) | 2023.07.19 |
[Javascipt] 함수 (0) | 2023.07.18 |
[Javascript] 구조 분해 할당과 선택적 체이닝 (0) | 2023.07.17 |
[Javascipt] 연산자 (0) | 2023.07.17 |