2.2 classμ κΈ°λ³Έ μ μΈ
μ΄μ ν¬μ€ν μμ μλ°μ€ν¬λ¦½νΈλ νλ‘ν νμ κΈ°λ°μ μΈμ΄λΌλ λ§μ νμμ΅λλ€. κ·Έλ¦¬κ³ es6μμ μΆνν class λν μ΄ κΈ°λ° μμμ λ³νλ ννμ λλ€. κ·ΈλΌ κΈ°μ‘΄μ νλ‘ν νμ μΌλ‘λ μ΄λ€μμΌλ‘ ν΄λμ€λ₯Ό νννλμ§ λΉκ΅ν΄λ³΄κ² μ΅λλ€.
(μ΄ κΈμ https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes λ΄μ©μ λ°νμΌλ‘ μμ±νμμ΅λλ€.)
class.js
1 2 3 4 5 6 7 8 | function Cat(name) { this.name = name; } Cat.prototype.speak = function () { console.log(this.name + ' makes a noise.'); }; | cs |
μ΄μκ°μ΄ functionμΌλ‘ μμ±μ νμμ΅λλ€. μ μ½λλ₯Ό 보면 Catμ΄λΌλ ν¨μκ° μκ³ κ·Έ ν¨μ(κ°μ²΄)λ₯Ό cλΌλ λ³μμ μ μΈν©λλ€.
κ·ΈλΌ c λ³μλ Cat μλ£νμ μλ speakλΌλ ν¨μμ μ κ·Όμ΄ κ°λ₯ν΄μ§λλ€. μλ§ classλ₯Ό μμλ λΆλ€μ΄λΌλ©΄ new μ°μ°μ μκΈ°λ₯Ό λ§μ΄ λ€μ΄λ³΄μ ¨μ κ²λλ€. μ°λ λ°©λ²μ λ€λ₯Έλ° κ±°μ κΈ°μ‘΄μ μλ classλ λΉμ·νκ² λμμ νκ³ μμ£ .
κ·ΈλΌ es6μ μΆκ°λ classλ‘λ μ΄λ»κ² λ°λλμ§ μμλ³΄κ² μ΅λλ€.
class.js
1 2 3 4 5 6 7 8 9 | class Cat{ constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } | cs |
λκ°μ λμμ νλλ° κΈ°μ‘΄μ classμ λν κ°λ μ μ’ μλ€λ©΄ μ΄ν΄κ° λλ ꡬ문μΌλ‘ λ°κΌμ΅λλ€.
Constructorμ λν μ€λͺ μ λ€μκ³Ό κ°μ΅λλ€.
Constructor (μμ±μ)
constructor
λ©μλλ class
λ‘ μμ±λ κ°μ²΄λ₯Ό μμ±νκ³ μ΄κΈ°ννκΈ° μν νΉμν λ©μλμ
λλ€. "constructor" λΌλ μ΄λ¦μ κ°μ§ νΉμν λ©μλλ ν΄λμ€ μμ ν κ°λ§ μ‘΄μ¬ν μ μμ΅λλ€. λ§μ½ ν΄λμ€μ ν κ°λ₯Ό μ΄κ³Όνλ constructor
λ©μλλ₯Ό ν¬ν¨νλ€λ©΄, SyntaxError
κ° λ°μν κ²μ
λλ€.
classμ λν μκΈ°λ₯Ό ν λ κΌ λμ€λ λ¨μ΄κ° μμ μ΄λΌλ λ¨μ΄μΈλ°μ κΈ°μ‘΄μ μμ±λ ν΄λμ€λ₯Ό μ¬μ¬μ©νλ λ°©λ²μ΄μ£ .
μλ°μμλ extendsλΌλ ν€μλλ‘ ν΄λμ€λ₯Ό μμλ°λλ°μ μλ°μ€ν¬λ¦½νΈμμλ λμΌν©λλ€.
class.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { super.speak(); console.log(this.name + ' barks.'); } } | cs |
Dog ν΄λμ€λ Animal ν΄λμ€λ₯Ό μμλ°μμΌλ―λ‘ super ν€μλλ₯Ό μ΄μ©νλ©΄ Animal ν΄λμ€μ speak ν¨μκ° νΈμΆλ©λλ€.
κ°μ²΄μ§ν₯ νλ‘κ·Έλλ°μ ν΄λ³΄μ λΆλ€μ΄λΌλ©΄ κ±°μ λμΌν λͺ¨μμ νκ³ μκΈ°λλ¬Έμ λ μ½κ² μ΄ν΄κ° κ°μ€κ±°λΌ μκ°ν©λλ€.