[Node.js 디자인패턴] 1주차

김련호·2021년 5월 5일
0

1. Node.js 철학

  • 경량 코어
  • 경량 모듈
  • 작은 외부 인터페이스
  • 간결함과 실용주의

2. Node.js 6와 ES2015에 대한 소개

  • let, const
    var와 달리 선언된 block scope으로 동작함
    let은 변수
    const는 상수. 할당된 값은 상수가 아님, 바인딩된 값은 상수
    const x = {};
    x.name = 'Kim'; // 할당 가능
    x = null;       // 오류
  • 화살표 함수
    function 함수 내부의 this는 해당 함수의 this 를 의미함
    화살표 함수의 this는 부모 블록의 this를 가리킴(화살표 함수 자체의 this를 가지지 않음)
    function greeter(name) {
      this.name = name;
    }

    greeter.prototype.greet1 = function () {
      setTimeout(function () {
        console.log("hello", this.name); // function 내부에 선언되어 있는 this는 있으나, name이라는 키를 가진 값은 없음
      }, 500);
    };

    greeter.prototype.greet2 = function () {
      setTimeout(
        function () {
          console.log("hello", this.name);
        }.bind(this), // 부모(greeter)의 this와 bind
        500
      );
    };

    greeter.prototype.greet3 = function () {
      setTimeout(() => {
        console.log("hello", this.name); // 부모(greeter)의 this에 접근 가능
      }, 500);
    };

    const g = new greeter("world");
    g.greet1(); // hello undefined
    g.greet2(); // hello world
    g.greet3(); // hello world
  • 클래스 구문
    다른 객체지향 언어와 거의 유사한 형태로 class, extends contructor, super 사용 가능함

  • 향상된 객체 리터럴

  // function 키워드 생략, 별도의 키 이름 생략
  module.exports = {
    square (x) {
      return x * x;
    },
    cube (x) {
      return x * x * x;
    }
  };

  // setter, getter 사용 가능
  const person = {
    name: "George",
    surname: "Boole",

    get fullname() {
      return `${this.name} ${this.surname}`;
    },

    set fullname(fullname) {
      const [name, surname] = fullname.split(" "); // array destructuring
      this.name = name;
      this.surname = surname;
    },
  };

  console.log(person.fullname); // George Boole
  console.log((person.fullname = "Alan Turing")); // Alan Turing
  console.log(person.name); // Alan
  • Map, Set Collection
    함수와 객체를 Map의 키로 사용할 수 있음. 이를 응용하여 테스트 프레임워크를 만들 수 있음.
    const tests = new Map();
    tests.set(() => 2 + 2, 4);
    tests.set(() => 2 * 2, 4);
    tests.set(() => 2 - 2, 1);

    for (const [test, result] of tests) { // array destructuring
      console.log(test() === result ? "PASS" : "FAIL");
    }

Set 또한 함수와 객체를 키로 사용할 수 있으며, 타 언어와 거의 유사한 기능을 가짐.

  • WeakMap, WeakSet Collection
    각 Collection이 가지고 있는 요소 전체를 탐색할 방법이 없음
    객체만을 키로 가질 수 있음
    키로 사용된 객체의 레퍼런스 카운트를 올리지 않기 때문에, 키 객체의 레퍼런스 카운트가 0이 되면 Collection 내에서 자동 삭제됨
    // Map
    let obj1 = { key: "val1" }; // ref count: 1
    const map = new Map();
    map.set(obj1, "obj1 value"); // obj1의 ref count: 2
    console.log(map); // Map(1) { { key: 'val1' } => 'obj1 value' }
    obj1 = undefined; // ref count: 1
    console.log(map); // Map(1) { { key: 'val1' } => 'obj1 value' }, obj1를 키로 사용하여 접근할 방법은 없지만 Map 내에 객체가 살아 있음

    // WeakMap
    let obj1 = { key: "val1" }; // ref count: 1
    const weakMap = new WeakMap();
    weakMap.set(obj1, "obj1 value"); // obj1의 ref count가 올라가지 않음. ref count: 1
    console.log(weakMap.has(obj1));
    obj1 = undefined; // ref count: 0, 객체 제거됨
    console.log(weakMap.has(obj1)); // undefined 를 사용하여 접근 불가. weakMap 내에 객체가 존재하지 않고, 접근할 방법도 없음.

3. Reactor 패턴

profile
기본이지만 잘 모르고 있던 것들, 모호한 것들을 기록합니다.

0개의 댓글