우아한 테크러닝 DAY 2

4 minute read

참고 !!
https://medium.com/ibare-story/e252506f8525 https://fastcampus-js-bootcamp.herokuapp.com/

자바스크립트

불변의 공리를 이해해야 한다
**변수 안에 값을 넣을 수 있다**

자바스크립트에서 함수

어떠한 값을 무조건 리턴해야만 한다

  • 함수 정의문 - if, switch, 분기, for, while, 반복
    값이 나오지 않는다, ;이 안붙는다
    fuction name(x){
      return y;
    }
    
  • 식 - *값이 나오는 것*, ;이 붙는다
    함수의 호출을 위임 : 콜백 함수
    const p = function name(x){
      return y;
    }
    

    함수의 종류

    함수도 객체를 확장한 것

  • 익명함수
    함수 이름은 참조값으로 시작되는 순간 없어지므로 이름 없는 함수로 나중에 실행이 불가능하다.
    fuction(){
      return y;
    }
    
  • 즉시함수
    한번만 실행하는 initialize 함수에 많이 사용한다.
    ```js (function(){ return y; })

const boo = function boo(){ boo(); //함수의 이름 } boo(); //변수의 이름 ; 참조값만 담김

- 콜백함수  
인자로 함수를 호출하는 것  
함수를 인자로 받고 함수를 실행하는 순간 만듦  
함수로 리턴  
= 값으로 통용되는 것들을 모두 변수로 넣을 수 있다! 가 논점  
= 함수는 코드를 묶고 있다!  
```js
function foo(){
    x();
    return funciton(){

    };
}
const y = foo(function(){

})
  • 재귀호출
    const foo = function foo(){
      foo()
    };
    
  • 함수의 변형(es6 이후)
  • 화살표함수 (람다식 한줄 함수) 함수는 인자를 받고 연산해서 돌려주는 것
    const x =10;    //값 
    const y = () => 10;    //계산
    const y = x => x*2; //로 () 생략할 수 있고
    const y = (x) => function(){};
    
  • new 연산자 동적바인딩
    const x ={}
    x.name = 10; //없는데 실시간으로 주는것
    
    function foo(){
      this.name = 10;
    }
    const y = new foo();
    

    instance 객체 객체임을 확인하면 다 확인해보지 않아도 객체라고 인정!
    ```js if (y instanceof foo){

}

- class
```js
function foo(){
    this.name = 10;
}
class bar{
    constructor(){
        this.name = 10;
    }
}
console.log(new bar()) // foo()는 new가 강제되지 않음 Foo 하면 new로 호출!!
//class는 무조건 new!!
  • this와 실행 컨텍스트 실행 컨텍스트가 아래와 같고 소유자는 this
    실행 컨텍스트는 전역 객체가 되면 안되므로 고정해야 한다
    bind, arrow 함수, call, apply로 고정할 수 있다.
    const person = {
      name: '조연우',
      getName() {
          return this.name;
      }
    
      const man = person.getName;
      console.log(man()) //이렇게 하면 name이 윈도우 값이 되어 오류 발생
    }
    
    const man = person.getName.bind(person);
    person.getName.call(person);
    //...
    
  • 클로저
    foo의 scope에 bar가 생김
    아래 코드에서 x가 클로저 역할 (scope내에서 밖의 변수를 가지고 있음)
    반환된 함수가 외부의 scope를 기억하는 상태
    foo가 끝나면 foo는 사라지지만 bar는 x를 기억
    값을 보호할 때 많이 씀
    ```js function foo(x){ return function bar(){ return x; }; }

const f = foo(10); console.log(f())

```js
const person = {
    age: 10,
}
function makePerson(){
    let age = 10;
    return {
        getAge(){
            return age;
        },
        setAge(x){
            age = x > 1 && x < 130 ? x : age;
        },
    };
}
let p = makePerson();
console.log(p.getAge());
  • 비동기와 promise
    setTimeout(function (x) {
      console.log("foo");
      setTimeout(function (y) {
          console.log("bar");
      }, 2000);
    }, 1000);
    

    위는 깊이 2지만 깊이가 깊어지면 콜백 헬이 발생하는데 이때 promise가 나온다.

    const p1 = new Promise((resolve, reject)=>{ //resolve와 reject 둘다 함수
      setTimeout(()=>{
          resolve("응답");
      }, 1000);
     // resolve();
     // reject();
    });
    p1.then(function(){
      console.log(r)//성공하면 이거 호출
    }).catch(function(){
      //실패하면 이거 호출
    })
    

    이거도 부족해서 동기처럼 펴는 것이 생긴게 아래

    const delay = ms => new Promise(resolve => setTimeout(resolve,ms));
    //promise 객체 리턴
    async function main (){
      console.log("1");
      await delay(2000);  //2초 딜레이 (전형적인 동기코드), 내부적으로는 비동기
      console.log("2");
    }
    main();
    

    자바스크립트는 싱글스레드라 동기로는 안된다.
    async await 사용한다면 try catch로 사용할 수 있다.

    try {
      const x = await delay(2000);
    } catch (e){
      console.log(e);
    }try {
      const x = await delay(2000);
    } catch (e){
      console.log(e);
    }
    
  • 커링 패턴
    위와 아래의 코드 결과는 같다. 위가 커링패턴이고 클로저는 항상 커링
    ```js function add(x){ return function(y){ return x + y; } } var first = add(1); // 함수를 반환합니다. first(2); // 3

function add(x,y){ return x+y; }

## redux
앱에서 쓰이는 모든 data 상태를 모아두고 data를 component한테 다 주자 그러고 store에서 저장하고 뽑아서 사용하도록 하자  
문제 ; 500개 중 하나만 바뀌어도 다 바꿔줘야 했음  
jsx -> react의 vdom 등장 ; vdom에 저장해두고 달라진 부분만 dom에 반영하도록 함  
redux는 이러한 그 상태관리자!!  
그걸 만든 것이 아래 코드  
store 하나, 그걸 만드는게 createStore  
data를 component가 못바꾸게 해야 한다!!  
return한 객체가 상태객체가 되지 않도록 해야함 ; 클로저로 상태를 숨기자  

\*\*redux.js\*\*
```js
export function createStore(reducer) {
    let state;
    const listener = [];
    const publish = () => {
        listener.forEach(({ subscriber, context }) => {
            subscriber.call(context);
        });
    };
    const dispatch = (action) => {
        state = reducer(state, action);
        publish();
    };
    const subscribe = (subscriber, context = null) => {
        listener.push({ subscriber, context });
    };
    const getState = () => ({ ...state });

    return {
        getState,
        dispatch,
        subscribe,
    };
}

export function actionCreator(type, payload = {}) {
    return {
        type,
        payload: { ...payload },
    };
}

index.js

import { createStore, actionCreator } from "./redux";

const INIT = "init";
const INCREMENT = "increment";
const RESET = "reset";

function reducer(state = {}, { type, payload }) {
    switch (type) {
        case INIT: {
            return {
                ...state,
                count: payload.count,
            };
        }
        case INCREMENT:
            return { ...state, count: state.count ? state.count + 1 : 1 };
        case RESET:
            return {
                ...state,
                count: 0,
            };
        default:
            return { ...state };
    }
}