20.08.18 [Scope, Async]

박종찬·2020년 8월 19일
0

TIL

목록 보기
16/89
post-thumbnail

3주 차 때 했었던 고차 함수를 underscore.js라는 기술을 가지고 모티브를 얻은 Underbar 과제를 시작했다. 결론은.. 3주 차에 했었던 고차 함수는 순한 맛이었던 걸로.. underbar는 아주 매운 맛처럼 느껴진다. 내가 멍충해진것 같다 ㅠㅠ..

  • 코드를 생성하고 실행하면 스코프에 따라 스코프 별로 excution context(메모리 테이블)를 생성한다.
    // global scope execution context -> 3 개 (a, func, this)
    // func scope execution context -> 2 개 (b, this)
    let a = 1;
    function func () {
    	let b = 10;
    }
  • execution context에는 4개의 정보가 담겨 있다.
    1. scope 내 변수 및 함수 (global, local)
    2. argument
    3. 호출된 근원(caller)
    4. this
  • Set 객체에 있는 값은 자기 이외의 값은 없다. 즉, 중복되는 값이 없다.
  • for ... of는 배열, for ... in은 객체
  • !undefined는 true
    • undefined === false 는 비교 대상의 타입이 달라서 false다.

비동기 호출

  • Blocking vs Non-Blocking
    • Blocking(전화)
      • 하던 일을 멈추고 받아야 한다.
      • 요청에 대한 결과가 동시에 일어난다. → synchronous
    • Non-Blocking(문자)
      • 확인 후, 나중에 답장할 수 있다.
      • 요청에 대한 결과가 동시에 일어나지 않는다. → asyncronous
  • setTimeout(callback, ms)
    • callback 함수, callback 함수 실행 전 기다려야할 시간 (ms)
  • setInterval(callback, ms)
    • callback 함수, 반복적으로 함수를 실행시키기 위한 시간 가격(ms)
  • clearInterval(timerId)
    • 반복 실행중인 타이머를 종료
  • clearTimeout
    • setTimeout에 대응하는 함수

this

  • 모든 함수 scope 내에서 자동으로 설정되는 특수한 식별자
  • execution context의 구성 요소 중 하나
  • 함수가 실행되는 동안 이용 가능하다.

this의 5가지 패턴

  1. Global : window
  2. Function Invocation : window, 부모가 window 라서
  3. Method Invocation : parent object
    • Method는 객체에 담긴 함수
    let obj = {
    	a : 10;
    	foo : function() {console.log(this)}
    }
    obj.foo(); // { a: 10, foo: [Function: foo] }
    ```

    ```jsx
    let obj = {
      fn: function (a, b) {
        return this;
      }
    };

    let obj2 = {
      method: obj.fn
    }

    // Point : 실행되는 시점
    console.log(obj2.method() === obj2); //true
    console.log(obj.fn() === obj); //true
  1. Construction mode (new 연산자로 생성된 function scope의 this) : 새로 생성된 객체
  2. .call, .apply 호출 : call, apply의 첫 번째 인자로 명시된 객체
    // .call
    let add = function (x, y) {
      this.sum = x + y;
    }

    let obj = {
      sum: 0
    };

    add.apply(obj, [2, 8]); // apply는 인자를 배열로 넘겨 준다.
    console.log(obj.sum);
    add.call(obj, 2, 8);
    console.log(obj.sum);
## bind

- call/apply와 다르게 함수를 바르게 실행시키지 않는다.
- this의 값이 바인딩된 **함수 자체**를 리턴한다.
        function Box(w, h) {
          this.width = w;
          this.height = h;

          this.getArea = function () {
            return this.width * this.height;
          }

          this.print = function () {
            console.log(this.getArea());
          }
        }

        let b = new Box(100, 50);
        b.print();

        // setTimeout(b.print, 1000); // TypeError
        setTimeout(b.print.bind(b), 1000);
profile
반가워요! 사람을 도우는 웹 개발자로 성장하기! :)

0개의 댓글