부트캠프/회고

[TIL] 프로그래머스 프론트엔드 데브코스 DAY12 TIL

Junly_21 2023. 10. 5. 13:28

공부한 내용 📖

생성자함수의 올바른 사용으로 객체를 생성하는법

function Car(name, brand) {
  this.name = name;
  this.brand = brand;
}

const Kia7 = new Car("K7", "KIA");
console.log(Kia7.name);

new를 붙여준다.

 

즉시실행함수의 사용방법과 뒤의 소괄호에 들어가는게 인자로 들어가서 매개변수로 전달된다.

this의 범위는 객체 내에서 보유여부를 통해 판단

var, let, const의 차이

클로저를 사용한 은닉화 복습

 

 

이벤트 캡처링과 버블링

 

아래 코드는 

fruits라는 id를 가진 ul아래에

one이라는 id를 가진 div 아래에

two라는 id를 가진 span을 넣고

 

fruits->one->two->two->one->fruits 순으로 캡처링과 버블링이 진행되는 과정의 eventTarget과 currentTarget을 확인해보려고 만든 코드이다.

 <body>
    <ul id="fruits">
      <li id="apple">Apple</li>
      <li id="banana">Banana</li>
      <li id="orange">Orange</li>
      <div id="one">
        1단계
        <span id="two">2단계</span>
      </div>
    </ul>
    <script>
      const $fruits = document.getElementById("fruits");
      const $banana = document.getElementById("banana");
      const one = document.getElementById("one");
      const two = document.getElementById("two");
      // #fruits 요소의 하위 요소인 li 요소를 클릭한 경우
      // 캡처링 단계의 이벤트를 캐치한다.
      $fruits.addEventListener(
        "click",
        (e) => {
          console.log("fruit");
          console.log(`이벤트 단계: ${e.eventPhase}`);
          console.log(`이벤트 타깃: ${e.target}`);
          console.log(`커런트 타깃: ${e.currentTarget}`); 
        },
        true
      );

      $fruits.addEventListener("click", (e) => {
        console.log("fruit");
        console.log(`이벤트 단계: ${e.eventPhase}`);
        console.log(`이벤트 타깃: ${e.target}`);
        console.log(`커런트 타깃: ${e.currentTarget}`);
      });

      one.addEventListener("click", (e) => {
        console.log("one");
        console.log(`이벤트 단계: ${e.eventPhase}`);
        console.log(`이벤트 타깃: ${e.target}`);
      });
      one.addEventListener(
        "click",
        (e) => {
          console.log("one");
          console.log(`이벤트 단계: ${e.eventPhase}`); 
          console.log(`이벤트 타깃: ${e.target}`); 
          console.log(`커런트 타깃: ${e.currentTarget}`); 
        },
        true
      );
      two.addEventListener(
        "click",
        (e) => {
          console.log("two");
          console.log(`이벤트 단계: ${e.eventPhase}`);
          console.log(`이벤트 타깃: ${e.target}`);
          console.log(`커런트 타깃: ${e.currentTarget}`); 
        },
        true
      );
      two.addEventListener("click", (e) => {
        console.log("two");
        console.log(`이벤트 단계: ${e.eventPhase}`);
        console.log(`이벤트 타깃: ${e.target}`); 
        console.log(`커런트 타깃: ${e.currentTarget}`); 
      });

    </script>
  </body>

결과는 다음과 같다.

 

'2단계' span을 눌렀더니 이벤트 타깃은 처음부터 끝까지 2단계의 태그인 Span을 유지한다. 다만 커런트 타깃은 이 클릭이벤트가 캡처링으로 내려갔다가 버블링으로 올라가는 과정의 현재 위치를 알려준다.

궁금한 내용/부족한 내용🤔

버블링과 캡처링을 실제로 어떻게 써먹을지는 아직 해보지 않아서 하다보면 알게되는걸까?

 

느낀점✍

하나하나의 개념은 모두 공부를 했던 것인데 (즉시실행함수, this, 클로저 등등)

JS코드를 주고 문제를 찾고 고쳐라. 라는 식의 퀴즈를 풀 때에는 이 개념들을 제대로 활용하지 못하고, 개념의 디테일이 부족하다고 느꼈다.

.