6-1. 자바스크립트의 클래스 소개

/** ES6 Class */

class Student {
  // constructor
  constructor(name, grade, age) {
    // fields(properties)
    this.name = name;
    this.grade = grade;
    this.age = age;
  }

  // methods
  study() {
    console.log("study");
  }
  introduce() {
    console.log("hi i'm", this.name);
  }
}

// Student Instance
let studentA = new Student("kihoon", "B", 25);
console.log(studentA);
studentA.study()
studentA.introduce();

class DeveloperStudent extends Student {
  constructor(name, grade, age, favoriteSkill) {
    // fields, using super
    super(name, grade, age);
    this.favoriteSkill = favoriteSkill;
  }

  // methods
  writeCode() {
    console.log(`${this.name} writing code using ${this.favoriteSkill}`);
  }
}

// DeveloperStudent Instance
const studentB = new DeveloperStudent('kihoon', 'B', 25, 'TypeScript');
studentB.study();
studentB.introduce();
studentB.writeCode();

JS 클래스에 더 공부해 보려면..

PoiemaWeb

Classes - JavaScript | MDN

6-2. 타입스크립트의 클래스

/** TS Class */
class Employee {
  // fields
  name: string;
  age: number;
  position: string;

  // constructor
  constructor(name: string, age: number, position: string) {
    this.name = name;
    this.age = age;
    this.position = position;
  }

  // methods
  work() {
    console.log("work");
  }
}

const employeeA = new Employee("kihoon", 25, "FE Engineer");
console.log(employeeA);

const employeeB: Employee = {
  name: "kihoon",
  age: 25,
  position: "FE Engineer",
  work() {},
};

class Manager extends Employee {
  // fields
  officeNumber: number;

  // constructor
  constructor(name: string, age: number, position: string, officeNumber: number) {
    super(name, age, position);
    this.officeNumber = officeNumber;
  }
}

6-3. 접근 제어자 access modifier

/** 접근 제어자 access modifier */

class Employee {
  // // fields
  // public name: string;
  // private age: number;
  // protected position: string;

  // // constructor
  // constructor(name: string, age: number, position: string) {
  //   this.name = name;
  //   this.age = age;
  //   this.position = position;
  // }

  constructor(
    public name: string,
    private age: number,
    protected position: string
  ) {}

  // methods
  work() {
    console.log(`${this.age} years old man is working.`);
  }
}

const employee = new Employee("kihoon", 25, "FE Engineer");
console.log(employee.name);
// console.log(employee.age); // error
// console.log(employee.position); // error
employee.work();

class ExtendedEmployee extends Employee {
  protectedTest() {
    console.log(`using ${this.position}`);
  }
  privateTest() {
    // console.log(`using ${this.age}`); // error
  }
}

public