Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- TypeScript
- git
- 머신러닝종류
- SSAFYcial
- 알고리즘
- VITE
- js
- pwa적용하기
- 백준
- SQL
- sqld
- 싸피셜
- Javascript
- 리액트
- vitepwa
- react
- db
- SSAFY
- PWA
- Python
- 데코레이터
- Django
- 플로이드워셜
- unionfind
- 싸피
- 14658
- 셀프넘버
- QuerySetAPI
- queryset
- 싸피10기
Archives
- Today
- Total
Meme's IT
[JS] 'this' keyword 본문
'this' keyword
함수나 메서드를 호출한 객체를 가리키는 키워드
함수 내에서 객체의 속성 및 메서드에 접근하기 위해 사용
파이썬의 self (인스턴스 자기자신)와 비슷함
const user = {
name: 'Yongbok',
geeting: fun () {
return `hello, ${this.name}`
}
}
// 호출
console.log(user.greeting()) // hello, Yonngbok
근데.. JavaScript에서 this는 함수를 호출하는 위치에 따라 가리키는 대상이 다름 → 호출될 때 결정됨(동적 할당)
- 단순 호출: 전역 객체
// 전역 객체
const myFun = function () {
return this
}
console.log(myFun()) // window: 가장 큰 전역 객체
// Node.js에서는 global이 전역 객체
- 함수에서 호출할 때
// (1) 일반 함수에서
const normalF = () => {
console.log(this) // window
}
normalF()
// (2) 객체 내부 메서드에서의 this
const obj2 = {
'name' : 'bok',
myFun: function() {
console.log(this) // this: 메서드가 정의된 객체
}
}
obj2.myFun()
// (3) 화살표 함수에서의 this
const arrowFun3 = () => {
console.log(this) // window
}
arrowFun3()
const obj3 = {
'name' : 'bok',
myFun: () => {
console.log(this) // 어라 얘도 window
}
}
obj3.myFun()
// (4) 생성자 함수 내부에서 this
function Person(name) {
this.name = name,
this.greeting = function() {
console.log(this)
}
}
const person1 = new Person('복')
const person2 = new Person('lash')
person1.greeting()
person2.greeting()
왜 화살표 함수는 계속 window?
→ 화살표 함수에서 this는 정의한 곳 기준으로 한 단계 상위에서 가져옴 (렉시컬 스코프 라고 함)
그러니까.... 객체 내부에서는 window를 쓰지말자
즉, JavaScript의 this는 호출되기 전까지 값이 할당되지 않고, 호출 시에 결정됨 (동적 할당)
헉 그럼 중첩되면 어떻게 해..?
# 중첩된 함수에서의 this
const myObj = {
numbers: [1, 2, 3],
myFun() {
console.log("this", this) // myObj
// 화살표 함수가 아닐 때,
// this.numbers.forEach(function (number) {
// console.log(this) // window, 단순호출이므로
// })
// 화살표 함수일 때,
this.numbers.forEach((number) => {
console.log(this) // myObj
})
}
}
myObj.myFun()
어지럽네...
forEach 내부의 콜백 함수로 사용된 익명함수는 밖으로 분리할 수 잇다.
일반 함수에서 this 참조와 동일 == Window
→ 콜백 함수는 화살표 함수를 사용하면 됨
화살표 함수는 자신만의 this를 가지지 않기 때문에 외부함수에서 가져 옴
아 몰라몰라 다 모르겠고 정리하자면
object에서는 화살표 함수를 쓰지말고, 콜백 함수에서는 화살표 함수를 쓰자
// object
const tmpObj = {
name: "test",
myFun() {
console.log(this.name) // test
}
}
tmpObj.myFun()
// 콜백 함수
const numbers = [1, 2, 3, 4, 5]
numbers.forEach((element) => {
console.log(element)
})
'FrontEnd > JavaScript' 카테고리의 다른 글
[JS] 이벤트 (0) | 2023.10.30 |
---|---|
[JS] 얕은 복사와 깊은 복사 (0) | 2023.10.26 |
[JS] 스코프 (1) | 2023.10.25 |
[JS] 배열(Array) (0) | 2023.10.25 |
[JS] JSON (0) | 2023.10.25 |