μμ±μ ν¨μ(prototype)
μμ±μ ν¨μμ μΌλ° ν¨μμ κΈ°μ μ μ°¨μ΄λ μλ€.
νμ§λ§ μμ±μ ν¨μλ λ κ°μ§ κ΄λ‘λ₯Ό λ°λΌμΌ νλ€.
- ν¨μ μ΄λ¦μ 첫 κΈμλ λλ¬Έμλ‘ μμνλ€.
- λ°λμ 'new' μ°μ°μλ₯Ό λΆμ¬μ€λ€.
μΌλ°μ μΈ ν¨μμ λͺ¨μ΅μ΄λ€.
λν 리ν°λ΄ λ°©μμΌλ‘ μ½λκ° μμ±λλ€.
리ν°λ΄ λ°©μ
μλ°μ€ν¬λ¦½νΈλ 리ν°λ΄ νκΈ°λ²μ μ΄μ©ν΄, νμν μμλ€μ μ΄κ±°νλ κ² λ§μΌλ‘ κ°μ²΄λ₯Ό λ§λ€ μ μλ€.
μ΄λ¬ν νκΈ°λ²μ JSONμλ μκ°μ μ£Όμλ€.
{ }, [ ], " " λ±μ μλ‘ λ€ μ μλ€.
const imae = {
firstName: 'Imae',
lastName: 'Kwak',
getFullName: function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(imae)
μ€ν κ²°κ³Ό
{
firstName: 'Imae',
lastName: 'Kwak',
getFullName: [Function: getFullName]
}
thisλ₯Ό μ¬μ©νλλ° λ€μ λΈλ‘κ·Έ κΈμμ μμΈν μμλ³Ό κ²μ΄λ€. μΌλ¨ λμ΄κ°μ.
μ€νκ²°κ³Ό imaeλΌλ λ³μμμ λ΄μ©μ΄ μΆλ ₯λλ κ²μ λ³Ό μ μλ€. firstName, lastName μ΄λΌλ λ κ°μ§ λ§€κ°λ³μλ₯Ό μ¬μ©ν λͺ¨μ΅λ λ³Ό μ μλ€.
const imae = {
firstName: 'Imae',
lastName: 'Kwak',
getFullName: function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(imae.getFullName())
μ€ν κ²°κ³Ό
Imae Kwak
getFullName() ν¨μλ₯Ό μ€νν κ²°κ³Ό, μ±κ³Ό μ΄λ¦μ΄ μ μμ μΌλ‘ μΆλ ₯λλ€.
const amy = {
firstName: 'Amy',
lastName: 'Clarke',
getFullName: function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(amy.getFullName())
const neo = {
firstName: 'Neo',
lastName: 'Smith',
getFullName: function () {
return `${this.firstName} ${this.lastName}`
}
}
console.log(neo.getFullName())
μ€ν κ²°κ³Ό
Amy Clarke
Neo Smith
μκΉμ κ°μ λ°©μμΌλ‘ λ κ°λ₯Ό λ λ§λ€μλ€.
μμ±μ ν¨μ λ°©μμ μ¬μ©νλ©΄ μ΄λ»κ² λ κΉ?
function User(first, last) {
this.firstName = first
this.lastName = last
}
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`
}
const imae = new User('imae', 'kwak')
const amy = new User('Amy', 'Clarke')
const neo = new User('Neo', 'Smith')
console.log(imae.getFullName()) // μμ±μ ν¨μ
console.log(amy.getFullName())
console.log(neo.getFullName())
μ€ν κ²°κ³Ό
imae kwak
Amy Clarke
Neo Smith
νΉμ§μ μΈ κ²μ μμμ μ΄ν΄λ³΄μλ―μ΄ ν¨μ μ΄λ¦μ 첫 κΈμλ λλ¬Έμλ‘ μμνκ³ , (User)
'new' μ°μ°μλ₯Ό λΆμ¬μ£Όμλ€.
λ νλμ νΉμ§μ prototypeμ λΆμ¬μ£Όμλ€λ κ²μ΄λ€.
prototype
λ€λ₯Έ μΈμ΄μ μ‘΄μ¬νλ classκ° Javascriptμλ μ‘΄μ¬νμ§ μλλ€.
λμ prototypeμ΄λΌλ κ²μ΄ μ‘΄μ¬νλ€.
javascriptμ λͺ¨λ κ°μ²΄λ prototypeμ΄λΌλ κ°μ²΄λ₯Ό κ°μ§κ³ μλ€.
λͺ¨λ κ°μ²΄λ κ·Έλ€μ νλ‘ν νμ μΌλ‘λΆν° νλ‘νΌν°μ λ©μλλ₯Ό μμμ λ°λλ€.
μ΄μ²λΌ μλ°μ€ν¬λ¦½νΈμ λͺ¨λ κ°μ²΄λ μ΅μν νλ μ΄μμ λ€λ₯Έ κ°μ²΄λ‘λΆν° μμμ λ°μΌλ©°,
μ΄λ μμλλ μ 보λ₯Ό μ 곡νλ κ°μ²΄λ₯Ό prototypeμ΄λΌκ³ νλ€.
'π€ Language > π¨ JavaScript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
JS. ES6 Classes (0) | 2022.02.15 |
---|---|
JS. this (0) | 2022.02.15 |
JS. μ½λ°±(CallBack) (0) | 2022.02.13 |
JS. νμ΄λ¨Έ ν¨μ (0) | 2022.02.13 |
JS. νΈμ΄μ€ν (0) | 2022.02.13 |