# 만약 Samgsung Store에서 판매자로 일하고 있고,
tv의 종류를 이름,가격,크기에 맞게 등록을 해야된다면?
수량이 많아질수록 너무 번거로운 작업들이 많아짐
let name = 'Sangsung Store'
let tv1 = {
name: 'Santino TV',
price: 200,
size: '26inch'
}
let tv2 = {
name: 'Martin TV',
price: 200,
size: '26inch'
}
let tv3 = {
name: 'Hyun TV',
price: 200,
size: '26inch'
}
console.log(tv1);
----------------------------
출력값 :
PS C:\Users\User\desktop\samsungTV> node main1.js
{ name: 'Santino TV', price: 200, size: '26inch' }
* tv1,tv2,tv3에서 중복되어 사용되는 값들(name,price,size)를 새로운 class에
묶어서 사용 가능함
+ constructure 사용해야 함
# constructure = 클래스에 있는 속성들의 값을 넣어주는 (초기화 시켜주는) 함수
class TV {
name='';
price=0;
size=''
constructor(name,price,size){ //constructure 생성자
this.name=name
this.price=price
this.size=size
}
}
// 여기서 new + 클래스 이름을 작성해주기
let tv1 = new TV('Santino TV', 200, '26inch')
* extends Product를 통해서, Product에 있는 내용들을 사용 가능
// let name = 'Sangsung Store'
class Product { // 추상화 abstraction
name='';
price='';
constructor(name,price){
this.name=name
this.price=price
}
}
class TV extends Product { // 상속 inheritance
size=''
constructor(name,price,size){ // constructure 생성자
super(name,price)
this.size=size
}
}
class AC extends Product {
option=''
}
class Computer extends Product {
color=''
}
let tv1 = new TV('Santino TV', 200, '26inch')
let tv2 = new TV('Martin TV', 300, '30inch')
// console.log(tv1);
-----------------------------
출력 :
PS C:\Users\User\desktop\samsungTV> node main1.js
TV { name: 'Santino TV', price: 200, size: '26inch' }
* 근데 200이 아니라, 200만원이라고 출력을 하고 싶다면?
getPrice()라는 함수를 만들어서 실행 가능
class Product {
name='';
price='';
constructor(name,price){
this.name=name
this.price=price
}
getPrice(){
return this.price+'만원'
}
}
class TV extends Product {
size=''
constructor(name,price,size){
super(name,price)
this.size=size
}
}
let tv1 = new TV('Santino TV', 200, '26inch')
console.log(tv1.getPrice());
-------------------------------------
출력: 200만원
* 만약 tv1.price = -1000;으로 설정을 잘못 했다면,(가격을 잘못 설정)
이대로 실행되지 않도록 확인할 수 있는 절차가 필요함.
let name = 'Sangsung Store'
class Product {
name='';
price='';
constructor(name,price){
this.name=name
this.price=price
}
getPrice(){
return this.price+'만원'
}
setPrice(price){ --- 이 부분 설정 필요
if(price<0){
throw Error('마이너스값 안됨')
}
this.price=price
}
}
class TV extends Product {
size=''
constructor(name,price,size){
super(name,price)
this.size=size
}
}
class AC extends Product {
option=''
}
class Computer extends Product {
color=''
}
let tv1 = new TV('Santino TV', 200, '26inch')
let tv2 = new TV('Martin TV', 300, '30inch')
tv1.setPrice(-1000);
console.log(tv1.getPrice()) --- 기존 Price로 실행하는게 아니라,
함수 setPrice()로 설정된 getPrice()를 실행하여,
원하지 않는 값을 출력하지 않도록 함
-------------------------------
출력:
PS C:\Users\User\desktop\samsungTV> node main1.js
C:\Users\User\desktop\samsungTV\main1.js:15
throw Error('마이너스값 안됨')
'FP OOP' 카테고리의 다른 글
FP (Functional Programming) (0) | 2023.03.15 |
---|