TIL (Today I Learned)
# class 대하여!.! 간단정리
k0z
2023. 12. 17. 00:33
# class 개념이 등장전
let name = 'samsung factory'
let tv1 = {
name: 'uhd tv',
price: 2000000,
size: '46inch'
}
let tv2 = {
name: 'ultratv',
price: 6700000,
size: '56inch'
}
let tv3 = {
name: 'grandtv',
size: '36inch'
}
# 클래스 기반 코드
실수를 줄이고 쉽게 만들기 위해 class 등장(작업지시서 아직 tv를 만들지는 않음)
// constructor 생성자 : 클래스에 있는 속성값을 초기화 시켜주는 기능 => 코드가 명료해짐
class TV {
constructor(name, price, size) {
this.name = name;
this.price = price;
this.size = size;
}
}
let tv1 = new TV('uhd tv', 2000000, '46inch');
let tv2 = new TV('ultratv', 6700000, '56inch');
5줄을 1줄로 끝내주며 자주 쓰는 걸 작업지시서로 만든 다음에 찍어 내듯이 만들 수 있음
안에 어떤 요소가 들어가 있는지 한번에 보기도 편함
# 추상화를 통한 공통 속성 정의( 클래스 기반 코드에 계속해서 추가)
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
class AC extends Product {
constructor(name, price, type) {
super(name, price);
this.type = type;
}
}
class Laptop extends Product {
constructor(name, price, weight) {
super(name, price);
this.weight = weight;
}
}
# Products 클래스에 기능 추가
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
getPrice() {
return `${this.price}원`;
}
setPrice(price) {
if (price < 0) {
throw new Error('마이너스값 안됨');
}
this.price = price;
}
}
# TV 클래스가 Products를 확장
class TV extends Product {
constructor(name, price, size) {
super(name, price);
this.size = size;
}
}