이번 글에서는 this의 사용법에 대해서 알아볼 것이다.
일반 함수(normal)는 호출 위치에 따라 this 정의
화살표 함수(Arrow)는 자신이 선언된 함수 범위에서 this 정의!
const flyda = {
name : 'flyda',
normal : function () {
console.log(this.name) //호출 위치에서 this 정의
},
arrow : () => {
console.log(this.name) // 자신이 선언된 함수 범위에서 this 정의, 지금 안에서 무엇을 지칭하는지 정확하게 알 수 없음.
}
}
flyda.normal() // flyda
flyda.arrow()//undefined
const amy = {
name : 'Amy',
normal : flyda.normal,//호출(실행)하는 것이 아니라 할당하는 구조라서 ()가 안붙음 !!
arrow : flyda.arrow
}
amy.normal() //Amy
amy.arrow() // undefined
여기에서 코드를 간단하게 수정할 수 있는데, normal : function () {} 부분에서 : function을 생략해 줄 수 있다. 수정한 코든 다음과 같다.
const flyda = {
name : 'flyda',
normal() { //function 키워드로 만들어진 일반함수와 동일함
console.log(this.name) //호출 위치에서 this 정의
},
arrow : () => {
console.log(this.name) // 자신이 선언된 함수 범위에서 this 정의, 지금 안에서 무엇을 지칭하는지 정확하게 알 수 없음.
}
}
flyda.normal() // flyda
flyda.arrow()//undefined
const amy = {
name : 'Amy',
normal : flyda.normal,//호출(실행)하는 것이 아니라 할당하는 구조라서 ()가 안붙음 !!
arrow : flyda.arrow
}
amy.normal() //Amy
amy.arrow() // undefined
생성자 함수에서 this 사용법!!
function User(name) {
this.name = name
}
User.prototype.normal = function () {
console.log(this.name)
}
User.prototype.arrow = () => {
console.log(this.name)
}
const flyda = new User('Flyda')
flyda.normal() //Flyda
flyda.arrow() //undefined
다른 예제
const timer = {
name : 'Flyda!!!!',
timeout: function () {
//setTimeout(함수, 시간밀리세컨)
setTimeout(function () {
console.log(this.name)
},2000)
}
}
timer.timeout()//undifined
여기에의 this는 일반 함수로 선언이 되어있어 호출 위치에서 정의가 된다. 그래서 setTimeout 함수의 내부로직으로 callback이 들어가서 어디선가 실행이 된다. 그래서 undefined가 출력되는 것! 만약 this.name이 timer객체데이터의 name 부분을 지칭해서 출력하기를 원했다면, 화살표 함수를 사용해 줘야 한다.
화살표 함수로 수정한 코드는 다음과 같다.
const timer = {
name : 'Flyda!!!!',
timeout: function () {
//setTimeout(함수, 시간밀리세컨)
setTimeout(() => {
console.log(this.name)
},2000)
}
}
timer.timeout()//Flyda!!!!
참고로 setTimeout 혹은 setInterval과 같은 타이머 함수를 사용할 경우 콜백으로 일반 함수보다 화살표 함수로 쓰는 것이 활용도가 높다!!
참고로 읽어야 하는 모던 자바스크립트 부분
- 메서드와 this : https://ko.javascript.info/object-methods
- 함수 바인딩 : https://ko.javascript.info/bind
- 화살표 함수 다시 살펴보기 : https://ko.javascript.info/arrow-functions
참고 : (KDT FE2) 한 번에 끝내는 프론트엔드 개발 초격차 패키지 Online 강의
'핀테크 서비스 프론트엔드 개발자 취업 완성 2기 > JS' 카테고리의 다른 글
[JS] 상속(확장) (0) | 2022.04.15 |
---|---|
[JS] ES6 Classes (0) | 2022.04.15 |
[JS] 클래스 - 생성자 함수 (prototype) (0) | 2022.04.15 |
[JS] 데이터 타입 확인 함수 (0) | 2022.04.14 |
[JS] Uncaught typeError: Failed to execute 'scrollTo' on 'window': the provided value is not of type 'scrollToOptions'. 해결방법 (0) | 2022.04.13 |
댓글