์๋ฐ์คํฌ๋ฆฝํธ๋ ํ๋กํ ํ์ ๊ธฐ๋ฐ ์ธ์ด๋ผ๊ณ ๋ถ๋ฆฐ๋ค. ํด๋์ค๊ฐ ์๋ ๋์ ๊ทธ ์ญํ ์ ํ๋ ํ๋กํ ํ์ ์ ์ฃผ๋ก ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ด๋ค. ํ๋กํ ํ์ ์ ๋ฌด์์ผ๊น?
๐ก Prototype
- ํ๋กํ ํ์ ์์ ํจ์์ ํจ์์ ํ๋กํผํฐ๋ฅผ ์์ฑํ๊ณ ๊ณต์ ํ ์ ์๋ค.
- ํ๋กํ ํ์ ์ new ํค์๋๋ก ๊ฐ์ฒด๋ฅผ ์์ฑํ์ฌ ๋ค๋ฅธ ๊ฐ์ฒด(ํจ์)๋ฅผ ์์ ๋ฐ์ ์ ์๋ค.
์ด๋ค ๊ฒฝ์ฐ์ ์ฌ์ฉํ ๊น?
function f1(){
return{
a: 10,
f: function(){}
}
}
let obj1 = f1();
let obj2 = f1();
console.log(obj1.f === obj2.f);
//false
- ์์ ํ๋ก๊ทธ๋จ์์ obj1๊ณผ obj2 ๊ฐ์ฒด๊ฐ ๋ค๋ฅด๋ค๊ณ ์ถ๋ ฅ๋๋ค.
- obj1๊ณผ obj2 ๋ ๋ชจ๋ f1 ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋๋ฐ ๋ ๊ฐ์ฒด๊ฐ ๋ค๋ฅด๋ค๊ณ ํ๋จ๋๋ ๊ฒ์ ์ฃผ์๊ฐ ๋ค๋ฅด๊ธฐ ๋๋ฌธ์ผ ๊ฒ์ด๋ค. ๊ฐ์ ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋๋ฐ ์ฃผ์๊ฐ ๋ค๋ฅด๋ค๋ ๊ฒ์ ๋นํจ์จ์ ์ด๋ค.
๐ก ์ฌ๊ธฐ์ ๋ ๊ฐ์ฒด๊ฐ ์ ๋ค๋ฅด๊ฒ ์ถ๋ ฅ๋๋ ๊ฑธ๊น?
- ์๋ฐ์คํฌ๋ฆฝํธ ์์์ ๋ค๋ฅด๊ฒ ์๊ฐํ๋ค๊ณ ํ๋ค.
- ์๋ฐ์์ new๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ์ฌ๋ฌ ๊ฐ ์์ฑํ๋ฉด ๋ฉ๋ชจ๋ฆฌ์์ญ์์ ์ฃผ์๊ฐ ๋ฌ๋ผ์ ธ์ ์๋ก ๋ค๋ฅธ ๊ฐ์ฒด๋ก ์๊ฐํ๋ ๊ฒ์ฒ๋ผ ์๋ฐ์คํฌ๋ฆฝํธ์์๋ ๊ทธ๋ฐ ๊ฒ๊ณผ ๋น์ทํ๊ฒ ์๋๊ฐ ์ถ๋ค.
- ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ํ๋กํ ํ์ ์ ์ฌ์ฉํด์ ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด์ ์ฌ์ฉํ๋ค.
// ํ๋กํ ํ์
function F2(){
this.a = 10
}
let ins1 = new F2();
let ins2 = new F2();
F2.prototype.f = function(){};
console.log(ins1.f === ins2.f);
// true
- ์์ฑ์ ํจ์๋ก F2()๋ฅผ ์์ฑํ๊ณ ํ๋กํ ํ์ ์ ์ด์ฉํด์ F2() ์ ํ๋กํผํฐ f ๋ฅผ ์์ฑํ๋ค.
- f ์ ์ ๊ทผํ๋ ๊ฐ์ฒด๋ ๋ชจ๋ ๋์ผํ๊ฒ ๋๋ค.
let obj = function f1(){}
obj.f1 = function(){
console.log(1);
}
obj.f1();
function F1(){
}
F1.prototype.f1 = function(){
console.log(2);
}
let ins = new F1();
ins.f1();
// 1
// 2
- F1() ํจ์๋ฅผ ์์ฑํ๊ณ prototype ์ผ๋ก ํจ์ F1 ์ ์์ f1์ ๋ง๋ ๋ค.
- ins ์ F1 ๊ฐ์ฒด๋ฅผ ์์ฑํ๊ณ f1์ ํธ์ถํ๋ค.
์์
// output() ์ผ๋ก ์คํ์ด ๋๊ฒ ๋ง๋ค๊ธฐ
function makeInfo(name, n1, n2) {
this.name = name,
this.n1 = n1,
this.n2 = n2
}
let ar = [];
ar.push(new makeInfo('ํธ๋์ด0', 10, 60));
ar.push(new makeInfo('ํธ๋์ด1', 20, 70));
ar.push(new makeInfo('ํธ๋์ด2', 30, 80));
ar.push(new makeInfo('ํธ๋์ด3', 40, 90));
ar.push(new makeInfo('ํธ๋์ด4', 50, 10));
ar.forEach((v, i) => {
ar[i].sum = v.n1 + v.n2;
})
for (let index in ar) {
ar[index].output();
}
- output() ์์ฑํ๋ ค๋ฉด ํ๋กํผํฐ๋ก ์์ฑํด์ผ ํ๋ค.
// output() ํ๋กํผํฐ ์์ฑ
makeInfo.prototype.output = function () {
console.log(this.name, this.n1, this.n2, this.sum);
}
- ar[index] ๊ฐ for ๋ฌธ์ผ๋ก ์ฒ์๋ถํฐ ๋๊น์ง ์ ๊ทผ์ ํ๊ธฐ ๋๋ฌธ์ ๊ฐ index ๋ฅผ ์ด๋ป๊ฒ output ํ๋กํผํฐ์ ์ ๋ฌํ ์ง๊ฐ ๊ณ ๋ฏผ์ด์๋๋ฐ this ๋ฅผ ์ฌ์ฉํด์ output ๋ด์์ ์ค์ค๋ก ํ์ฌ index ๋ฅผ ์ฐพ๋๋ก ํ๋ค.
- output ํ๋กํผํฐ ์์ฑํ๊ณ this ๋ก index ์ ๋ง๋ ๋ณ์ ๊ฐ์ ์ถ๋ ฅํ๋ค.
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Babel ์ด๋? (0) | 2022.05.11 |
---|---|
addEventListener ์ด๋ฒคํธ (input & change) (0) | 2022.04.25 |
[JavaScript] ๋๋ฒ๊ฑฐ ์๋ฌ ํด๊ฒฐ (0) | 2021.09.30 |
[JavaScript] ์๋ฐ ์คํฌ๋ฆฝํธ ํจ์ (0) | 2021.09.30 |
[JavaScript] ์๋ฐ ์คํฌ๋ฆฝํธ ๊ธฐ๋ณธ ํจ์ (0) | 2021.09.29 |
๋๊ธ