[Node.js] 구조분해 할당과 클래스

말하는 감자·2024년 3월 3일
0
post-thumbnail

[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지

섹션 1. 알아두어야 할 자바스크립트

📌 구조분해 할당

옛날엔 비구조화 할당이였는데 최근에 번역이 구조분해 할당으로 변경되었다.

const example = { a : 123, b : { c : 135, d : 146} };

const a = example.a;
const d = example.b.d;

속성 이름을 변수로 만들어주는 상황이 자주 발생한다.
example은 나중에 사용을 안하게 되거나 값들을 꺼내기 위하 중간 다리 역할을 하게 되는 경우가 발생한다.

아래와 같은 문법으로 변경 가능하다.

const { a, b : { d }} = example;

console.log(a);	// 123
console.log(d);	// 146

이를 구조분해 문법이라고 한다.
배열도 구조분해 문법 사용이 가능하다.

const arr = [1, 2, 3, 4, 5];

const x = arr[0];
const y = arr[1];
const z = arr[4];

위의 코드를 아래로 변경가능하다.

const [x, , , y, z] = arr;

변수를 배열의 자릿수를 맞춰주면 된다.

this가 있는 경우에는 구조분해 할당에 문제가 발생한다. this는 함수를 호출할 때 어떻게 호출되었냐에 따라 결정되기 때문이다. 그래서 this가 있을 때는 구조분해 할당을 안하는 게 좋다.

📌 클래스

클래스는 프로토타입 문법을 깔끔하게 만들어주는 것이다. 즉, 클래스는 프로토타입이다. 클래스를 알려면 프로토타입도 알아야한다.

// 생성자(Constructor) - 주로 대문자로 선언한다.
var Human = function(type) {
  this.type = type  || 'human';
};

// 스태틱 메서드 / 생성자 메서드
Human.isHuman = function(human) { 
  return human instanceof Human;
};

// 인스턴스 메서드 / 프로토타입 메서드
Human.prototype.breathe = function() {
  alert('h-a-a-a-m');
};

// 상속
var Zero = function(type, firstName, lastName) {
  Human.apply(this, arguments);
  this.firstName = firstName;
  this.lastName = lastName;
};

Zero.prototype = Object.create(Human.prototype);
Zero.prototype.constructor = Zero; // 상속하는 부분
Zero.prototype.sayName = function() {
  alert(this.firstName + ' ' + this.lastName);
};
var oldZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(oldZero); // true

생성자와 메서드가 하나의 단위로 관리 되지 않아 헷갈리기 쉽다.
상속하려면 부모로부터 apply를 받아야 하고 Object생성도 필요하다.

위의 코드를 클래스를 통해 아래와 같이 깔끔하게 변경 가능하다.

class Human {
  constructor(type = 'human') {
    this.type  = type;
  }
  
  static isHuman(human) {
    return human instanceof Human;
  }
  
  breathe() {
    alert('h-a-a-a-m');
  }
}

// 상속
class Zero extends Human {
  constructor(type, firstName, lastName) {
    super(type);
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  sayName() {
    super.breathe();
    alert(`${this.firstName} ${this.lastName}`);
  }
}

const newZero = new Zero('human', 'Zero', 'Cho');
Human.isHuman(newZero); // true

클래스를 사용하게 되면 메서드들이 한 곳에서 관리되기 때문에 가독성이 좋아진다.
또한 extends를 통해 쉽게 상속이 가능해진다.
super를 사용하여 부모 함수를 쉽게 불러올 수 있다. 위 코드에서 super(type)을 통해 Human 클래스의 constructor 부분이 실행되고 super.breathe()를 통해 breathe() 함수가 실행된다.


📑 출처

  • [개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지 (인프런/조현영)
profile
나는 말하는 감자다

0개의 댓글