Notice
Recent Posts
Recent Comments
Link
솔미는 성장중
[JS] This 본문
728x90
메소드(객체 내 함수) this -> 객체
함수 this -> window object
constructor function this -> 빈 객체를 가리킴 (여기다가 속성을 넣는거)
화살표 함수 this -> 상위 스코프 this
- 일반 함수의 this
: 호출 위치에서 정의
: 아래 예제에서 this → PPAP로 바꿔주어도 결과가 동일
: 즉! this = getFullName이라는 속성이 들어있는 객체 데이터
const PPAP = {
front: 'PenPineapple',
end: 'ApplePen',
getFullName: function() {
return `${this.front} ${this.end}`
}
}
console.log(PPAP.getFullName()) //PenPineapple ApplePen
: 축약 가능. 즉, 일반함수의 경우 :(콜론) 과 function을 함께 지워줄 수 있다.
getFullName () {
return `${this.front} ${this.end}`
}
- 화살표 함수의 this
: 자신이 선언된 함수(렉시컬=함수가 동작할 수 있는 유효한 범위) 범위 에서 정의
(쉽게 말하면 this가 선언된 함수 외부에 또 다른 함수를 기준으로 한다는 뜻)
: 일반 함수의 경우와 달리 축약 불가능.
: 특정 함수 내부에서 this 키워드를 반복적으로 쓸 땐(함수내에 함수가 있는 경우), 일반함수보다 화살표 함수가 적합하다.
const PPAP = {
front: 'PenPineapple',
end: 'ApplePen',
getFullName: () => {
return `${this.front} ${this.end}`
}
}
console.log(PPAP.getFullName()) //undefined undefined
위 예제에서 일반함수를 화살표 함수 형태로 바꿨을 뿐인데 undefined가 나온다.
왜냐하면 화살표 함수를 감싼 또 다른 함수가 없는 상태이기 때문!
따라서 의도한대로 작동하도록 수정하면..
function PPAP() {
this.front = 'I have a pen'
this.end = 'You have an apple'
return {
front: 'PenPineapple',
end: 'ApplePen',
getFullName: () => {
return `${this.front} ${this.end}`
}
}
}
const p = PPAP()
console.log(p.getFullName()) //I have a pen You have an apple
getFullName이라는 메소드에 함수를 할당하는데, 그 함수가 화살표 함수라면 this키워드는 외부 함수를 참조한다.
cf) 위 코드를 실행하는 데 문제가 생긴다면 확인해볼 것
1) index.html에서 script태그에 type="module"이 있는지 확인
: module이 추가되어있다면 자동으로 strict type이 되어 제대로 작동하지 않을 수도 있다. 이를 지워준다.
2) 밑에서 2번째 줄에 const p = PPAP()라고 쓴 것에 new 붙여주기
const p = new PPAP()
다른 예시)
const timer = {
name: 'Ming',
timeout: function () {
setTimeout(() => {
console.log(this.name) //여기서 this는 일반함수를 가리킴. 이는 곧 timer을 가리킴
},2000)
}
}
timer.timeout()
🎯 용어 체크
속성 : 객체 데이터 속에 함수 데이터가 할당된 것이 아닌 것
메소드 : 할당되는 데이터가 함수인 경우
멤버 : 속성+메소드
+) 특정 개체에서 다른 개체의 메소드를 빌려와 사용하는 방법
- 우선 일반함수로 작성하여야 한다. (화살표 함수 X)
- call 함수를 사용해 불러온다.
function PPAP() {
this.front = 'Apple'
this.end = 'Pen'
return {
front: 'PenPineapple',
end: 'ApplePen',
getFullName () {
return `${this.front} ${this.end}`
}
}
}
const ppap2 = {
front : 'Pineapple',
end : 'Pen'
}
const p = PPAP()
console.log(p.getFullName()) //PenPineapple ApplePen
console.log(p.getFullName.call(ppap2)) //Pineapple Pen
가장 마지막 줄을 확인하면 된다.
getFullName을 실행하는 데 거기에 들어갈 것은 ppap2라는 것을 call함수를 통해 표현해주었다.
728x90
'JavaScript > 함수' 카테고리의 다른 글
[JS] 호출 스케줄링 ( 타이밍 함수 ) (0) | 2023.07.18 |
---|---|
[JS] 함수 : 재귀 (0) | 2023.07.18 |
[JS] 콜백 (callback) 함수 (예시 포함) (0) | 2023.07.18 |
[JS] 즉시 실행 함수 (IIFE) (0) | 2023.07.18 |
[JS] 함수 선언 : 화살표 함수 (0) | 2023.07.18 |