[Javascript] Prototype μ ν΅ν μμ κ³Ό __proto__ +(MDN μμ λ‘ λ³΄λ Prototype μμ)
μλ°μ€ν¬λ¦½νΈμμ classλ?
μμ±μν¨μ μμ±
ν¨μ νΈμΆ
κ°μ²΄ μμ±
μ λ΄λΆ ꡬν
ν¬λ‘±μ μμ κ³Ό μνμ½λ© js κ°μ²΄μ§ν₯ νλ‘κ·Έλλ°μ μ°Έμ‘°νμ¬
MDNμ μλ Class Model μμμμ -> Constructor function κ³Ό prototypeμ μ΄μ©νμ¬ μμμ ꡬνν΄ λ³΄μλ€.
Class λ₯Ό μ΄μ©ν μμ
Javascriptλ νλ‘ν νμ based μΈμ΄
μλλ class κ° μκΈ° μ μ μμ±μ ν¨μλ₯Ό μ΄μ©νμ¬ μμμ ꡬννλ€.
λ°λΌμ Class μ extends λ₯Ό νλ‘ν νμ μ ν΅ν΄ ꡬνν΄λ³΄μ
Constructor function (μμ±μ ν¨μ) λ° κ°μ²΄ μμ±
1) Car (λΆλͺ¨) , Model (μμ) μ΄λΌλ μμ±μ ν¨μ μμ±
κ°μμ Prototype κ°μ²΄κ° μμ±λ¨ ( Car's prototype , Model's prototype)
2) New μ°μ°μλ₯Ό μ΄μ©ν΄ mycar κ°μ²΄ μμ±
__proto__
: κ°μ²΄κ° κ°μ§κ² λλ μμ±
: μμ μ μμ±ν μμ±μ ν¨μμ Prototype μ΄ κ°λ¦¬ν¨ κ°μ²΄λ₯Ό κ°λ¦¬ν€κ² λ¨
3) mycar.show() νΈμΆ
1) mycar.show() μ°ΎκΈ° -> X
2) __proto__κ°λ¦¬ν€λ show() μ°ΎκΈ° -> O
Modelμ showλ₯Ό 보면 Carμ λ©μλ μΈ presentλ₯Ό μ¬μ©νλλ° μλ‘ μ°κ²°μ΄ λμ΄μμ§ μμμ undefined
λΆλͺ¨μ μμ Prototype κ°μ²΄ μ°κ²°
Model μ νλ‘ν νμ κ°μ²΄μ __proto__ Carμ νλ‘ν νμ κ°μ²΄λ₯Ό κ°λ¦¬ν€κ² νλ©΄ λλ€
λΉνμ€ λ°©μ : Model.prototype.__proto__ = Car.prototype
* Model.prototype.__proto__κ° Car νλ‘ν νμ κ°μ²΄λ₯Ό κ°λ¦¬ν€κ²ν¨
* __(μΈλλ°)λ‘ μμνλ κ²μ μ§μ νΈμΆνμ§ μλκ²μ΄ μ’λ€κ³ νκΈ° λλ¬Έμ λ€λ₯Έλ°©λ²μ μ΄μ©νλ κ²μ΄ μ’μ
Object.create() λ°©μ
Model.prototype.show = Object.create(Car.prototype)
__proto__κ° Carνλ‘ν νμ κ°μ²΄λ₯Ό κ°λ¦¬ν€λ μλ‘μ΄ Model νλ‘νΌνμ κ°μ²΄λ₯Ό μμ±νλ€.
μ΄ λ§λ€μ΄μ§ μλ‘μ΄ κ°μ²΄μ __proto__ λ Carνλ‘ν νμ κ°μ²΄λ₯Ό κ°λ¦¬ν€κΈ° λλ¬Έμ
present() λ₯Ό μ¬μ©ν μ μκ² λ©λλ€.
λΆλͺ¨(Car) μμ± μ μμ(Model)μμ μ¬μ©
Car.call (this, brand)
Model.show ν¨μλ κ²°κ΅ this.present() μμ Car μ μμ±μ μ¬μ©νκΈ° λλ¬Έμ
Carμ μμλ€μ κ°μ Έμμ μ¬μ©ν΄μΌν¨ -> Car ν¨μλ₯Ό μ€ν
Car.call (this, brand)
Carμ thisλ₯Ό Model λ‘ λ§λ κ°μ²΄λ‘ λ°κΏμ μ€ν μν΄μΌλ‘μ¨ Carμ μμλ₯Ό Modelμμ μ¬μ©ν¨
( * Carμ thisλ Carμμμμ thisμ΄κΈ° λλ¬Έμ Modelμμ λ§λ€μ΄μ§ mycarμ΄λΌλ κ°μ²΄λ‘ λ°κΏμ μ€ν)
μ΄λ κ² μ§μ prototypeμ μ΄μ©ν΄ μμκ΄κ³λ₯Ό ꡬνν¨μΌλ‘μ¨ prototype κ³Ό __ptoro__μ κΈ°λ₯μ λμΌλ‘ νμΈνλ€.
νμ§λ§ μ΄λ κ² μ΄ν΄λ νμ§λ§ λ§λ‘ μ€λͺ νκΈ°λ λ μ΄λ €μ prototypeμ μλ―Έμ κ·Έ μ₯μ μ νλ§λλ‘ μ λ¦¬ν΄ λ³΄μλ€.
Prototype
ν¨μκ° μ μΈλ λ μλμΌλ‘ μ μΈλλ μμ± κ°μ²΄
μ¬μ©νλ μ΄μ
Constructor function (μμ±μν¨μ)κ°λ§λ λͺ¨λ κ°μ²΄λ prototypeμ ν΅ν΄ μ μΈλ μμ±κ³Ό λ©μλλ₯Ό 곡μ ν¨
μ½λ μ¬μ¬μ© -> λ©λͺ¨λ¦¬ ν¨μ¨ λμμ§
νλ‘ν νμ μ λν λλ§μ μ μλ₯Ό νλ©° μ΄λ²κΈμ λ§λ¬΄λ¦¬!