객체지향이란? 4가지 특성 (자바스크립트)

haley·2023년 4월 11일
0

객체지향이란?

  • 프로그래밍 방식 중 하나 (=코드를 정리하는 방식 중 하나)
  • 데이터와 데이터와 연관된 기능을 클래스로 캡슐화하여 프로그래밍하는 방식
  • 데이터: 붕어빵 재료, 클래스: 붕어빵 틀, 객체: 붕어빵

네가지 특성

  1. 캡슐화 (encapsulation)
  • 데이터, 데이터와 관련된 함수를 캡슐(클래스)안에 담는것
  • 코드가 구조적으로 변함, 재사용이 편리해진다
  • 노출할 자료와 숨길 자료를 선택할 수 있다 (은닉성) 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();
  1. 상속 (inheritance)
  • 부모클래스의 속성을 자식클래스가 물려받는 것
  • 여러 클래스에서 공통된 부분을 뽑아 상위 클래스를 만들고, 이를 하위 클래스에서 상속받아 사용할수 있다.
  • 중복을 제거하고 재사용성 좋아짐
//공통 클래스 만듦
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`
  }
}
  
  1. 추상화 (abstraction)
  • 구현 세부 정보를 숨긴채 인터페이스를 만드는 행위
//클래스 및 인터페이스 생성
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(); //세부 구현사항을 몰라도 배열을 수정할수 있음
  1. 다형성 (polymorphism)
  • 부모로부터 상속받은 속성을 오버라이딩해서 다른 형태로 바꿀수 있는 특성
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 생성
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: 팥
profile
기록장

0개의 댓글