TIL

dev-wholΒ·2021λ…„ 6μ›” 14일
0

✍🏻 클래슀λ₯Ό μ΄μš©ν•œ λͺ¨λ“ˆν™”

객체 지ν–₯

객체 지ν–₯ ν”„λ‘œκ·Έλž˜λ°μ΄λž€?

  • ν•˜λ‚˜μ˜ 청사진을 λ§Œλ“€κ³  청사진을 λ°”νƒ•μœΌλ‘œ ν•œ 객체λ₯Ό λ§Œλ“œλŠ” ν”„λ‘œκ·Έλž˜λ° νŒ¨ν„΄
    ex) 청사진(class) : μžλ™μ°¨λ₯Ό λ§Œλ“œλŠ” 섀계도(ν•Έλ“€,바퀴,엔진 λ“±) / 객체(instance) : λΈŒλžœλ“œ,이름,색깔 λ“±

ν΄λž˜μŠ€μ™€ μΈμŠ€ν„΄μŠ€

  • ν΄λž˜μŠ€λŠ” μΌμ’…μ˜ μ›ν˜•μœΌλ‘œ, 객체λ₯Ό μƒμ„±ν•˜κΈ° μœ„ν•œ μ•„μ΄λ””μ–΄λ‚˜ 청사진
  • μΈμŠ€ν„΄μŠ€λŠ” 클래슀의 사둀(instance object)
  • ν΄λž˜μŠ€λŠ” 객체λ₯Ό λ§Œλ“€κΈ° μœ„ν•œ μƒμ„±μž ν•¨μˆ˜λ₯Ό 포함
prototypeλͺ¨λΈμ˜ 청사진을 λ§Œλ“€ λ•Œ μ“°λŠ” μ›ν˜• 객체(original form)
constructorμΈμŠ€ν„΄μŠ€κ°€ μ΄ˆκΈ°ν™”λ  λ•Œ μ‹€ν–‰ν•˜λŠ” μƒμ„±μž ν•¨μˆ˜
thisν•¨μˆ˜κ°€ 싀행될 λ•Œ, ν•΄λ‹Ή scopeλ§ˆλ‹€ μƒμ„±λ˜λŠ” κ³ μœ ν•œ μ‹€ν–‰ context(execution context)
class Car { // 클래슀
   constructor(brand, name, color){ // μΈμŠ€ν„΄μŠ€
     this.brand = brand;
     this.name = name;
     this.color = color;
   }
   refuel() {
   console.log(`${this.name}κ°€ μ—°λ£Œλ₯Ό μ£Όμž…ν•©λ‹ˆλ‹€`)
   }
   drive() {
   console.log(`${this.name}κ°€ μš΄μ „μ„ μ‹œμž‘ν•©λ‹ˆλ‹€`)
   }
 }
 let tesla = new Car('tesla', 'model y', 'black');
 console.log(tesla) // Car {brand: "tesla", name: "model y", color: "black"}
 console.log(tesla.drive()) // model yκ°€ μš΄μ „μ„ μ‹œμž‘ν•©λ‹ˆλ‹€ 
  • 속성과 λ©”μ†Œλ“œ
    속성 : brand,name,color
    λ©”μ†Œλ“œ : refuel(),drive()

절차적 μ–Έμ–΄λž€?

  • 초기의 ν”„λ‘œκ·Έλž˜λ° μ–Έμ–΄λŠ” 일반적으둜 절차적 μ–Έμ–΄(C,ν¬νŠΈλž€ λ“±)
  • 절차적 μ–Έμ–΄λŠ” 순차적인 λͺ…λ Ήμ˜ μ‘°ν•©
    ex) 객체 지ν–₯의 κ°œλ…μ΄ μ—†λŠ” 절차 μ–Έμ–΄

OOP(Object-Oriented Programming)

  • OOPλŠ” ν”„λ‘œκ·Έλž¨ 섀계 μ² ν•™ 쀑 ν•˜λ‚˜
  • OOP의 λͺ¨λ“  것은 "객체"둜 κ·Έλ£Ήν™”
  • OOP의 4가지 μ£Όμš” κ°œλ…μ„ 톡해 μ–»λŠ” μž¬μ‚¬μš©μ„±

OOP Basic Concepts

  • Encapsulation(μΊ‘μŠν™”)
    • 데이터(속성)와 κΈ°λŠ₯(λ©”μ†Œλ“œ)을 ν•˜λ‚˜μ˜ λ‹¨μœ„λ‘œ λ¬ΆλŠ” 것
    • 은닉(hiding): λ‚΄λΆ€ λ°μ΄ν„°λ‚˜ λ‚΄λΆ€ κ΅¬ν˜„μ€ 숨기며 μ™ΈλΆ€μ—μ„œ ν•„μš”ν•œ λ™μž‘(λ©”μ†Œλ“œ)은 λ…ΈμΆœ
    • λŠμŠ¨ν•œ κ²°ν•©(Loose Coupling)에 유리 : κ΅¬ν˜„ μˆ˜μ •μ— 용이
  • Inheritance(상속)
    • κΈ°λ³Έ 클래슀의 νŠΉμ§•μ„ νŒŒμƒ ν΄λž˜μŠ€κ°€ λ¬Όλ €λ°›λŠ” 것
  • Absraction(좔상화)
    • λ‚΄λΆ€ κ΅¬ν˜„μ€ λ³΅μž‘ν•˜μ§€λ§Œ μ‹€μ œλ‘œ λ…ΈμΆœλ˜λŠ” 뢀뢄은 λ‹¨μˆœν™”ν•˜κ²Œ λ§Œλ“œλŠ” κ°œλ…
      ex) μ „ν™”κΈ° λ‚΄λΆ€μ—λŠ” λ§Žμ€ λΆ€ν’ˆμ΄ λ“€μ–΄μžˆμ§€λ§Œ μ‚¬μš©μžμ—κ²ŒλŠ” μˆ˜ν™”κΈ°μ™€ λ²„νŠΌ λ“±μœΌλ‘œ μΈν„°νŽ˜μ΄μŠ€λ₯Ό λ‹¨μˆœν™” ν•˜λŠ” 것
  • Polymorphism(λ‹€ν˜•μ„±)
    • λ™μΌν•œ λ©”μ†Œλ“œμ— λŒ€ν•΄ 객체의 νŠΉμ„±μ— 맞게 각기 λ‹€λ₯΄κ²Œ μž‘μ„±ν•˜λŠ” 것이 κ°€λŠ₯

ν”„λ‘œν† νƒ€μž…(Prototype)

ν”„λ‘œν† νƒ€μž…μ΄λž€?

  • μ›ν˜• 객체λ₯Ό 의미

ν”„λ‘œν† νƒ€μž… 체인

class Human{
  constructor(name,sex,age){
    this.name = name;
    this.sex = sex;
    this.age = age;
  }
  sleep(){
    console.log(this.name + '은(λŠ”) 자고 μžˆλ‹€')
  }
  eat(){
    console.log(this.name + "은(λŠ”) λ¨Ήκ³  μžˆλ‹€")
  }
}
class Student extends Human{
  constructor(name,sex,age,learning){
    super(name,sex,age)
      this.learning = 'Math'
  }
  learn(){
    console.log(this.name +'은 '+ this.learning + '을 배우고 μžˆλ‹€');
  }
}

0개의 λŒ“κΈ€