과거 프로그래밍 자료들/Javascript&typescript
모던 자바스크립트 핵심 가이드 02 화살표 함수
평부
2022. 5. 12. 10:09
* 모던 자바스크립트 핵심 가이드(저자 알베르토 몬탈레시, 옮김 임지순/권영재) 복습
* 핵심 부분과 필요할 경우 문제도 수정해서 기재할 것
* 문제될 경우 삭제할 것
○ 화살표 함수
- 화살표 함수 = 익명 함수
- 참조할 이름 필요 = 함수를 변수에 할당 (여기서는 name)
//변경 전
const animal1 = function(name) {
return "안녕하세요" + name;
}
//변경 후
const animal2 = (name) => {
return "안녕하세요" + name;
}
//매개변수가 하나만 있으면 괄호 생략 가능
const animal3 = name => {
return "안녕하세요" + name;
}
//매개변수가 없으면 빈 괄호
const animal4 = () => {
return "안녕하세요";
}
//암시적 반환도 가능
const aniaml5 = name => `안녕하세요 ${name}`; //return 생략
○ 객체 리터럴 암시적 반환
const webtoon = "전지적 독자 시점";
const characters = ['김독자', '유중혁', '한수영'];
const results = characters.map((character, i) => ({name: character, webtoon, place: i +1}));
console.log(results);
//{name: "김독자", place: 1, webtoon: "전지적 독자 시점"}
//{name: "유중혁", place: 2, webtoon: "전지적 독자 시점"}
//{name: "한수영", place: 3, webtoon: "전지적 독자 시점"}
○ 화살표 함수 내부에서 this 키워드 사용 -> 상위 스코프에 상속됨
//수정 전
//HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>helloo</title>
<style>
.opening {
background-color: red;
}
</style>
</head>
<body>
<div class="box opening">
This is box
</div>
<script>
//box 클래스 가진 div 가져옴
const box = document.querySelector(".box");
//click 이벤트 핸들러 등록
box.addEventListener("click", function() {
//div에 opening 클래스 토글
this.classList.toggle("opening");
setTimeout(function() {
//클래스를 다시 토글
this.classList.toggle("opening");
}, 500);
})
//this는 window로 설정되서 에러 발생
</script>
</body>
</html>
//수정 후
//HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>helloo</title>
<style>
.opening {
background-color: red;
}
</style>
</head>
<body>
<div class="box opening">
This is box
</div>
<script>
//box 클래스 가진 div 가져옴
const box = document.querySelector(".box");
//click 이벤트 핸들러 등록
box.addEventListener("click", function() {
//div에 opening 클래스 토글
this.classList.toggle("opening");
setTimeout(() => { //이 부분 수정
//클래스를 다시 토글
this.classList.toggle("opening"); //this는 const box
}, 500);
})
</script>
</body>
</html>
○ 화살표 함수 피해야 하는 경우
자세한 설명:
화살표 함수와 this 바인딩 (https://velog.io/@padoling/JavaScript-%ED%99%94%EC%82%B4%ED%91%9C-%ED%95%A8%EC%88%98%EC%99%80-this-%EB%B0%94%EC%9D%B8%EB%94%A9)
- 메소드
- 생성자 함수
- addEventListener()의 콜백함수
//메소드(오류)
const phone = {
name: 'samsung';
callName: () => console.log(this.name);
}
phone.callName(); // undefined
//생성자 함수(오류)
const Netflix = () => {};
const netflix = new Netflix(); // TypeError: Netflix is not a constructor
//addEventListener()의 콜백함수
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log(this); // Window
this.innerHTML = 'clicked';
});
button.addEventListener('click', function() {
console.log(this); // button 엘리먼트
this.innerHTML = 'clicked';
});