TypeScript는 JavaScript의 superset이다. 따라서 JS를 제대로 알아야 TS도 잘 쓸수가 있다. TS에서도 사용되는 JS의 주요 개념 세가지 - Prototype, this, module을 리뷰하고 넘어가자.

Prototype


Every Object in JS Has a Parent Object Called Prototype

Moreover, every object in JS actually inherits “Object” prototype

const array = [];
console.log(array);

Untitled

Untitled

Untitled

Implementing Inheritance with Prototype

// function으로 생성자 함수(클래스 역할) 정의
function CoffeeMachine(beans) {
  this.beans = beans;
  // Instance member level
  this.roastBeans = (grams) => {
    console.log('roasting...');
  };
}

// Prototype member level
CoffeeMachine.prototype.makeCoffee = (shots) => {
  console.log('making...');
};

// new 키워드로 인스턴스 생성
const machine1 = new CoffeeMachine(10);
console.log(machine1);
machine1.roastBeans(1);
machine1.makeCoffee(1);

function LatteMachine(milk) {
  this.milk = milk;
}
// Inheriting CoffeeMachine
LatteMachine.prototype = Object.create(CoffeeMachine.prototype);

const latteMachine1 = new LatteMachine();
console.log(latteMachine1);
latteMachine1.makeCoffee(1);

Untitled

Instance level vs. Prototype level