본 게시물은 한빛미디어의 "모던 자바스크립트 핵심 가이드"(알베르토 몬탈레시 지음)를 공부하면서 작성되었습니다.
이전 글: [JS 핵심 가이드] 01. var, let, const
02. 화살표 함수
2.4 화살표함수와 this 키워드
: 화살표 함수를 사용할 때 this 키워드는 상위 스코프에서 상속된다.
- 활용할 수 있는 경우
// HTML
<div class="box open">
This is a box
</div>
//CSS
.opening {
background-color: red;
}
// Javascript w/ function()
const box = document.querySelector(".box")
box.addEventListener("click", function() {
this.classList.toggle("opening") // ① this
setTimeout(function() {
this.classList.toggle("opening") // ② this
}, 500)
});
=> 이 때, 첫 번째 ① this 은 const box에 할당되었지만, setTimeout 내부의 두 번째 ② this 는 Window 객체로 설정되어 오류가 발생한다.(Uncaught TypeError: cannot read property "toggle" of undefined)
Javascript의 setTimeout을 화살표 함수로 바꾸어 작성했을 때
// Javascript setTimeout w/ arrow function
const box = document.querySelector(".box")
box.addEventListener("click", function() {
this.classList.toggle("opening") // ① this
setTimeout(() => {
this.classList.toggle("opening") // ② this
}, 500)
});
=> 두 번째 ② this 는 부모로부터 상속되므로 const box로 설정된다.
2.5 화살표 함수를 피해야 하는 경우
const button = document.querySelector(".btn")
button.addEventListener("click", () => {
this.classList.toggle("on"); // Error!
});
이 경우는 코드의 의도대로라면 this가 const button을 가리켜서 정상적으로 해당 클래스("on")가 button이 가리키는 html 태그에 토글로 동작하는 것일 것이다.
하지만, 여기서 this는 화살표함수로 작성되었기 때문에, Window객체를 가리키게 된다. 따라서 에러가 발생한다.
- 화살표 함수와 일반함수의 또다른 차이점: arguments 객체에 대한 접근 방식
( arguments 객체: 함수 내부에서 접근할 수 있는 배열 객체 )
this 키워드와 비슷하게, 화살표 함수에서 arguments 객체는 부모 스코프의 값을 상속함
arguments를 받는 기초 예시
function example() {
console.log(arguments[0];
}
example(1, 2, 3)
오류가 나는 코드 ( ReferenceError: arguments is not defined )
const showWinner = () => {
const winner = argument[0];
console.log(`${winner} was the winner`);
};
showWinner("Kim", "Lee", "Park")
=> 함수에 전달된 모든 인수에 접근하려면, 기존 함수 표기법이나 스프레드 문법을 사용하면 된다.
화살표 함수로 arguments에 접근하는 예
const showWinner = (...args) => {
const winner = args[0]
console.log(`${winner) is the winner`)
};
showWinner("Kim", "Lee", "Park") // Kim is the winner'2) 개발 > JavaScript' 카테고리의 다른 글
| [JS 핵심 가이드] 04. 템플릿 리터럴( 부제: 백틱(`)을 사용하여 문자열을 삽입하는 여러가지 방법 ) (0) | 2021.10.25 |
|---|---|
| [JS 핵심 가이드] 03. 함수 기본값 인수 (0) | 2021.10.25 |
| [JS 핵심 가이드] 01. var, let, const (0) | 2021.10.22 |
| [JS 핵심 가이드] 00. 자바스크립트 기초 (0) | 2021.10.22 |
| [JS 핵심 가이드] 0. 목차 소개 (0) | 2021.10.21 |