해당 포스트는 제로베이스 오프라인스쿨 진행 과정 중 JS PairProgramming과제를 진행하며 회고를 정리하는 글이다.
02 Counter TIL
1. 클로저를 만드는 방식
매개 변수로 함수를 받아와서 쓰는 방식
const counter = (() => {
const $counter = document.querySelector('.counter');
let count = 0;
return (aux) => {
aux(count);
return count;
}
})();
increase(_count) => {
count += _count;
return count;
}
decrease(_count) => {
count -= _count !== 0 ? 1 : 0;
return count;
}
자유변수 count를 조작하는 함수를 객체 담아서 return 하는 방식
const counter = (() => {
const $counter = document.querySelector('.counter');
let count = 0;
return {
increase() {
count += 1;
$counter.textContent = count;
},
decrease() {
if (count > 0) count -= 1;
$counter.textContent = count;
},
};
})();
위 방식보다 아래 방식은 더 알아보기 쉽다. 또한 위 방식에서 increase 함수를 호출해 count를 증가시키려면
counter(increase);
이렇게 counter 함수를 호출하면서 increase 함수를 인자로 넘겨주어야 하지만, 아래 방식은 더 직관적으로 쓸 수 있다.
counter.increase();
또한 Count 문제에서는 count 변수를 단순 증감시키는 거싱 아니라, 화면에 렌더링하는 것까지 목표이기 때문에 단순히 count 변수를 반환하는 것이 아니라 바로 count 변수를 그리도록 한다.
2. 삼함연산자를 쓰는 경우
decrease() {
count -= count !== 0 ? 1 : 0;
$counter.textContent = count;
}
if 문을 쓰는 경우
decrease() {
if (count > 0) count -= 1;
$counter.textContent = count;
}
위 경우는 삼항연산자로 쓰는 것보다 if 문을 쓰는 것이 더 가독성 좋고 직관적인 코드이다.
<배운점>
++ 코드를 작성한 사람만이 이해하는 코드는 좋은 코드라고 할 수 없다. 코드를 작성하지 않는 사람도 쉽게 이해할 수 있는 코드를 만들어야 한다고 생각했다.
'JavaScript > PairProgramming1 회고' 카테고리의 다른 글
StopWatch (0) | 2023.05.09 |
---|---|
PopupModal (0) | 2023.05.09 |
DarkMode (0) | 2023.05.09 |
Is Palindrome (0) | 2023.05.09 |
Scrolling Go To Top (0) | 2023.05.09 |