Study/끄적끄적

Typescript) OOP 기본

Juzdalua 2022. 6. 17. 14:18

 

// Typescript

// 추상화
abstract class Product{
  name: string;
  price: number;

  constructor(name: string, price: number){
    this.name = name;
    this.price = price;
  }
}

// 상속
export class TV extends Product{
  size: number;

  constructor(name: string, price: number, size: number){
    super(name, price)
    this.size = size;
  }
}

export class Laptop extends Product{
  weight: number;

  constructor(name: string, price: number, weight: number){
    super(name, price); // 부모 클래스 호출
    this.weight = weight;
  }

  // 캡슐화
  getWeight(){
    return `${this.weight}Kg`
  }

  setWeight(weight: number){
    if(weight < 0){
      throw Error
    }
    this.weight = weight
  }
}

const samsungTv = new TV('SSTV', 300, 56);
console.log(samsungTv);

const samsungLaptop = new Laptop('SSNOTEBOOK', 100, 3);
console.log(samsungLaptop.name, samsungLaptop.getWeight());

 

// Javascript

class Person{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

const kim = new Person('jun', 33);
logger.info(kim);