데브코스 TIL - DAY 11,12

조주영·2021년 8월 17일
0

데브코스-TIL

목록 보기
12/34

DAY 11

자가진단

스코프와 클로저의 이해, var const let의 차이에 대해 설명 할 수 있는가?
var(함수단위평가,재할당가능)
let(블럭단위평가,재할당가능)
const(블럭단위평가,재할당불가능)

앞 til에서도 다뤘던 스코프와 클로저 였지만, 글과 말로 설명하려니 시간이 꽤 오래 걸렸다. 따라서 다시한번 글로 쓰면서 복습하려고 한다.....

스코프

유효범위. 즉 변수에 접근 할 수 있는 범위를 의미한다.

클로저

    function makeFunc() {
      var name = "Mozilla";
      function displayName() {
        alert(name);
      }
      return displayName;
    }

    var myFunc = makeFunc();
    //myFunc변수에 displayName을 리턴함
    //유효범위의 어휘적 환경을 유지
    myFunc();
    //리턴된 displayName 함수를 실행(name 변수에 접근)

코드출처: MDN
이처럼 myFunc에 의해 makeFunc()가 실행이되고, 이때 makeFunc는 리던하는 display(name)의 어휘적인 참조를 유지한다. 이때 클로저가 만들어지고,
myFunc()를 실행 시키면 displayName함수를 실행시켜 name변수에 접근하여 'mozilla'를 결과값으로 낸다.

DAY 12 명령형,선언형 프로그래밍

명령형 프로그래밍

컴퓨터가 수행할 명령들을 순서대로 써 놓은 것이다.
키워드를 지시
ex)식당들어가서 밥을 먹는 과정을 생각!
또한 어떻게 구현하는가를 디테일하게 기술하는 것에 관점이 가있다.

EX)코드

function double(arr){
    let results =[]
    for (let i =0; i<arr.length;i++){
        if(typeof arr[i]==='number'){
            arr.push(arr[i]*2)
        }
    }
}

선언적인 프로그래밍 방식의 이해

ex)html sql
html
우리는 특정 태그를 쓰면, 구현할 필요없이 브라우저가 화면을 그리는 것을 다 처리해준다.
sql
우리가 query를 주면, sql이 내부적으로 동작해 데이터를 뽑아다 준다.

EX코드)

function double(arr){
    return arr.filter(param=> typeof param==='number')
                .map(number=>number*2)
}

이처럼 명령형은,어떻게 가공할 것인가? 에 대한 고민이 중요하고,
선언은 무엇을 할것이냐가 중요한 시점의 차이라고 볼 수 있다.

ex) 아래처럼, 3개의 버튼을 만들고 조작한다고 했을때,

const $button1 = document.createElement('button');
$button1.textContent='Button1';

const $button2 = document.createElement('button');
$button2.textContent='Button2';

const $button3 = document.createElement('button');
$button3.textContent='Button3';


//만든 버튼을 화면에 그린다.
const $main = document.querySelector('#app')
$main.appendChild($button1)
$main.appendChild($button2)
$main.appendChild($button3)

이때, 클릭한 버튼은 line-through를 통해 text에 줄을 긋고,
줄이 그어져 있는 버튼을 클릭하면 줄을 지우게끔 만들고자 한다면,

명령형 코드는 다음과 같은 로직을 작성할 수 있다.

$button1.addEventListener('click', ()=>{
    if($button1.style.textDecoration==='line-through'){
        $button1.style.textDecoration='none'
    }
    else{
        $button1.style.textDecoration='line-through'
    }
})
$button2.addEventListener('click', ()=>{
    if($button2.style.textDecoration==='line-through'){
        $button2.style.textDecoration='none'
    }
    else{
        $button2.style.textDecoration='line-through'
    }
})
$button3.addEventListener('click', ()=>{
    if($button3.style.textDecoration==='line-through'){
        $button3.style.textDecoration='none'
    }
    else{
        $button3.style.textDecoration='line-through'
    }
})

그러나 명령형은 이처럼, 버튼이하나 생성될떄마다, 하나씩 만들어줘야 한다.

반면에 선언형은,

document.querySelectorAll('button').forEach(
    $button=>{
    $button.addEventListener('click',(e)=>{
        const { target } = e
        if(target.style.textDecoration ==='line-through'){
            target.style.textDecoration='none'
        }
        else{
            target.style.textDecoration='line-through'
     }
    }
    )})

같지만 조금더 축약이 된다. 그러나 이것을 조금더 직관적이고 이해하기 쉽게 추상화 하는것이 선언형의 목표임으로, 이것을 고처보면,

function ToggleButton({
    $target,
    text
}) {
    //target에 버튼추가
    const $button = document.createElement('button');
    $target.appendChild($button)
  //버튼에 렌더링에 필요한부분을 다시그림
    this.render = () => {
        $button.textContent = text
}
    //버튼이 눌렸을때 이벤트
   $button.addEventListener('click', () => {
        if ($button.style.textDecoration === 'line-through') {
            $button.style.textDecoration = ''
        } else {
            $button.style.textDecoration = 'line-through'
        }
    })
  this.render()
}
const $app = document.querySelector('#app')
new ToggleButton({
    $target: $app,
    text : 'Button1'
})
new ToggleButton({
    $target: $app,
    text : 'Button2'
})
new ToggleButton({
    $target: $app,
    text : 'Button3'
})
new ToggleButton({
    $target: $body,
    text : 'Button4'
})

그러나 이것도 ToggleButton을 만들어 버튼이 추가될때마다, 객체를 만들어주어 사용 할 수 있다. 이것 또한 번거롭게 느껴질 수 있으므로,

//버튼생성 함수
function ButtonGroup({
    $target,
    buttons
})
{
    const $group = document.createElement('div')
    let isInit = false

    this.render = () =>{
        if(!isInit){
            buttons.forEach(({ type, ...props})=>{
                if (type==='toggle'){
                   new ToggleButton(
                     {$target: $group, ...props}) 
                }
                            
            })

            $target.appendChild($group)
            isInit = true
        }
    }
    this.render()
}
//버튼 생성
new ButtonGroup({
    $target: $app,
    buttons:[
        {
            type:'toggle',
            text:'토클 버튼'
        },
        {
            type:'toggle',
            text:'토클 버튼'
        },

ButtonGroup 함수를 만들어, 한번에 버튼을 생성하여 추상화하는 것이 추후 기능추가, 오류찾기등 직관적이라 관리가 쉬워진다.
이것이 선언형프로그램을 사용하는 이유이다!!

느낀점

자가진단을 하면서, 기본적인 내용을 스스로에게 되물어 봤을때 선뜻대답을 하기 쉽지 않았다. 아마 내가 알고 있다고 생각한 부분이라 더욱 평소에 생각하지 않게 되는 것 같다.
기본기의 탄탄함을 목표로 세우고 있는데, 정작 기본기를 소홀히 하고 있던 나........
앞으로 이렇게 스스로 되물어보면서, 대답하는 시간을 꾸준히 가져야 겠고, 그런 위주의 포스팅을 해야겠다.
til은 말그대로 내가 오늘 배운것이니까.....
오늘도 많은 것을 배우면서 끝.

profile
꾸준히 성장하기

0개의 댓글