public, private
//캡슐화 전
const enterpreneur = {
firstName: "Elon",
lastName: "Musk",
shares: 177000000,
company: "TSLA",
}
function calculateNetWorth(shares, company) {
const sharePrice = getSharePrice(company);
return shares * sharePrice;
}
//캡슐화
class Enterpreneur {
constructor(
private firstName: string,
private lastName: string,
private shares: number,
private company: string
) {}
public calculateNetWorth(){
return this.shares * getSharePrice(this.company);
}
}
//사용
const elon = new Enterpreneur("Elon","Musk",177000000,"TSLA");
elon.calculateNetWorth();
//공통 클래스 만듦
class Human {
constructor(name) {
this.name = name;
this.arms = 2;
this.legs = 2;
}
}
//Baby는 Human클래스의 속성을 상속받음
class Baby extends Human {
constructor(name) {
super(name); //상속받기 위해 super method 호출필요
this.cute = true;
}
cry(){
return `waa waa`;
}
}
//Teenager는 Human 클래스의 속성을 상속받음
class Teenager extends Human {
constructor(name) {
super(name);
this.emotional = true;
}
curse(){
return `asdfasdf`
}
}
//클래스 및 인터페이스 생성
class BetterArray {
private items: string[];
constructor() {
this.items = [];
}
//인터페이스 1
public getItems() {
return [...this.items];
}
//인터페이스 2
public addItem(item: string) {
this.items.push(item);
}
public modifyItem(itemToChange: string, newValue: string) {
const index = this.items.indexOf(itemToChange);
if (index !== -1) {
this.items[index] = newValue;
}
}
}
//사용
const arr = new BetterArray();
arr.addItem("hihihi");
arr.modifyItem(); //세부 구현사항을 몰라도 배열을 수정할수 있음
class Person {
public sayHi() {
return "✋✋"
}
public sayBye() {
return "✌️✌️"
}
}
class 한국인 extends Person{}
class Italian extends Person{}
class 적용 전
const 붕어 = {
이름: "기본 붕어빵",
속재료: "팥",
익힘정도: 90,
가격: 1000
}
const 크림붕어 = {
이름: "크림 붕어빵",
속재료: "슈크림",
익힘정도: 85,
가격: 1500
}
const 바싹익은붕어 = {
이름: "기본 붕어빵",
속재료: "팥",
익힘정도: 100,
가격: 1000
}
class 적용 후
//class 생성
class 붕어빵 {
constructor(이름, 속재료, 익힘정도, 가격) {
this.이름 = 이름;
this.속재료 = 속재료;
this.익힘정도 = 익힘정도;
this.가격 = 가격
}
//메서드 생성
sayPrice(){
return `${this.이름}의 가격은 ${this.가격}원 입니다.`
}
}
//객체 생성
const 붕어 = new 붕어빵("기본 붕어빵", "팥", 90, 1000);
const 크림붕어 = new 붕어빵("크림 붕어빵", "슈크림", 85, 1500);
const 바싹익은붕어 = new 붕어빵("기본 붕어빵","팥", 100, 1000);
//속성 접근 가능
console.log(붕어.속재료); //output: 팥