JAMONGPROJECT

220427 본문

Challenge/엘리스 SW Engineer 2기

220427

JAMONGPROJECT 2022. 4. 27. 17:36

let도 호이스팅이 된다.

 

호이스팅이란 ? 

 

변수 선언부분만 상단으로 끌어올려지는 현상

 

변수 값 입력은 나중에 된다.

 

클로저란?

 

함수가 선언되었을 당시의 렉시컬 환경을 기억하는 것.

 

함수가 실행되고 소멸되더라도 참조할 수 있는 영역은 남아있다.

 

 

전역변수를 잘 쓰지 않는 이유 

- 이후에 관리가 힘들다. 그래서 함수 내부에서 선언을 많이함.

그래서 클로저 개념이 필요하다.

 

단점 : 메모리가 계속 유지되기 때문에 메모리 누수 현상이 일어난다.

 

클로저 예제

 

function clickHandler() {
  let count = 0;

  const increase = function () {
    console.log(++count);
  };

  const decrease = function () {
    console.log(--count);
  };

  return [increase, decrease];
}

const [increaser, decreaser] = clickHandler();
// distructure 라는 테크닉.

const countUpBtn = document.querySelector(".count-up-btn");
countUpBtn.addEventListener("click", increaser);

const countDownBtn = document.querySelector(".count-down-btn");
countDownBtn.addEventListener("click", decreaser);

 

 

-> 같은 환경에서 같은 count 라는 변수를 공유하기때문에 count++와 count-- 를 동시에 사용할 수 있다. 

 

 

 

실습 1. this와 []를 통한 메소드 호출

 

class Menu {
  // 지시사항을 참고하여 코드를 작성하세요.
  handleEvent(event) {
    let method = "on" + event.type[0].toUpperCase() + event.type.slice(1);
     this[method](); // == this.onMousedown or onMouseup()
  }    

  onMousedown() {
    elem.innerHTML = "마우스 버튼을 눌렀습니다."
  }

  onMouseup() {
    elem.innerHTML = "마우스 버튼을 뗐습니다."
  }
}

let menu = new Menu();
const elem = document.getElementById("elem");
elem.addEventListener("mousedown", menu);
elem.addEventListener("mouseup", menu);

'Challenge > 엘리스 SW Engineer 2기' 카테고리의 다른 글

220504  (0) 2022.05.04
220502  (0) 2022.05.02
220425  (0) 2022.04.26
자동차 경주 문제  (0) 2022.04.23
220420  (0) 2022.04.20
Comments