์ด๊ฑฐ๋ณด๊ณ prototype ์ดํด ๋ชปํ๋ฉด ๊ฐ์์ ์ ์ฐธ๊ณ
'์ ์ ์'๋ผ๊ณ ์ดํดํ ๊ฒ
๋ถ๋ชจ Me๋ name = 'syong'์ ๊ฐ์ง. ๋ถ๋ชจ Me์ ์ํด ํ์ด๋ ์์ I๋ name = 'syong'์.
// ํ๋กํ ํ์
function Me () {
this.a = 'a';
this.b = 'b';
}
Me.prototype.name = 'syong';
const I = new Me();
console.log(I); // {a = 'a', b = 'b'}
console.log(I.name); // syong
์ํ์ฝ๋ฉ 2014 prototype ๊ฐ์ ์ฐธ๊ณ
prototype์ ์ ์ฅ๋ ์์ฑ๋ค์
์์ฑ์๋ฅผ ํตํด์ ๊ฐ์ฒด๊ฐ ๋ง๋ค์ด์ง ๋
๊ทธ ๊ฐ์ฒด์ ์ฐ๊ฒฐ๋๋ค.
[ ์์ 1 ]
function Ultra () {}
Ultra.prototype.ultraProp = true;
function Super () {}
Super.prototype = new Ultra();
function Sub () {}
Sub.prototype = new Super();
Sub.prototype.ultraProp = 2;
var o = new Sub();
console.log(o.ultraProp); // 2
์์ฑ์ Sub์ prototype ๊ฐ์ฒด
๋ฅผ ๋ค์ง๋ค. ์์ฑ์ Sub์ prototype ๊ฐ์ฒด์์ ultraProp ํ๋กํผํฐ๋ฅผ ๋ฐ๊ฒฌํ๊ณ ๊ทธ ๊ฐ์ ์ถ๋ ฅํ๋ค.[ ์์ 2 ]
function Ultra () {}
Ultra.prototype.ultraProp = true;
function Super () {}
Super.prototype = new Ultra();
function Sub () {}
var s = new Super();
s.ultraProp = 3;
Sub.prototype = s;
var o = new Sub();
console.log(o.ultraProp); // 3
์์ฑ์ Sub์ prototype ๊ฐ์ฒด
๋ฅผ ๋ค์ง๋ค. ์์ฑ์ Sub์ prototype ๊ฐ์ฒด์ ๋ณ์ s๊ฐ ํ ๋น๋์ด ์๋ค. ๋ณ์ s์๋ ์์ฑ์ Super๊ฐ ๋ง๋ ๊ฐ์ฒด๊ฐ ํ ๋น๋์ด ์๋ค. ๊ทธ ๊ฐ์ฒด์ prototype ํ๋กํผํฐ๊ฐ 3์ด๋ฏ๋ก ์ด๋ฅผ ์ถ๋ ฅํ๋ค.[ ์์ 3 ]
function Ultra () {}
Ultra.prototype.ultraProp = true;
function Super () {}
var t = new Ultra();
t.ultraProp = 4;
Super.prototype = t;
function Sub () {}
var s = new Super();
Sub.prototype = s;
var o = new Sub();
console.log(o.ultraProp); // 4
์์ฑ์ Super์ prototype ๊ฐ์ฒด
๋ฅผ ๋ค์ง๋ค. ์์ ๊ฐ์ ๊ณผ์ ์ ๊ฑฐ์ณ 4๋ฅผ ์ถ๋ ฅํ๋ค.๐ก ์ฃผ์ !
Sub.prototype = new Super(); // (o) Sub.prototype = Super.prototype; // (x)
๋ ๋ฒ์งธ์ฒ๋ผ ์์ฑํ๋ฉด, Sub์ prototype ๊ฐ์ฒด์ ์ด๋ค ํ๋กํผํฐ๋ฅผ ์ถ๊ฐํ ๋ Super์ prototype ๊ฐ์ฒด๋ ์ํฅ์ ๋ฐ๊ฒ ๋๋ค. ์ฆ, ์์ ๊ฐ์ฒด์ ์ด๋ ํ ๊ธฐ๋ฅ์ ์ถ๊ฐํ๋ฉด ๋ถ๋ชจ ๊ฐ์ฒด์๋ ๊ฐ์ ๊ธฐ๋ฅ์ด ์ถ๊ฐ๋์ด ๋ฌธ์ ๊ฐ ๋ฐ์ํ ์ ์๋ค.
์๋ฐ์คํฌ๋ฆฝํธ๋ ์๋ฐ์คํฌ๋ฆฝํธ๊ฐ ๋์ํ๋ ํธ์คํธ ํ๊ฒฝ์ด, ๊ฐ๋ฐ์๋ค์๊ฒ ๊ธฐ๋ณธ์ ์ผ๋ก ์ ๊ณตํ๋, ๋ฏธ๋ฆฌ ๋ง๋ค์ด์ ธ ์๋ ๊ฐ์ฒด
Object, Function, Array, String, Boolean, Number, Math, Date, RegExp(์ ๊ทํํ์)
// ์์ 1 - ๋ฐฐ์ด ์์ ๋๋คํ๊ฒ ๊ฐ์ ธ์ค๊ธฐ
{
const arr = new Array('I', 'my', 'me', 'mine');
function getRandomValueFromArray () {
const index = Math.floor(arr.length * Math.random());
return arr[index];
}
console.log(getRandomValueFromArray());
}
// ์์ 1 - ํ์ค ๋ด์ฅ ๊ฐ์ฒด์ ํ์ฅ
Array.prototype.random = function () {
const index = Math.floor(this.length * Math.random());
return this[index];
}
const arr = new Array('I', 'my', 'me', 'mine');
console.log(arr.random());
prototype
์ ์ด์ฉํด ๋ชจ๋ ๋ฐฐ์ด์ ๊ณตํต์ ์ผ๋ก ์ธ ์ ์๋ API
๋ฅผ ์ฌ์ฉ์๊ฐ ์ง์ ์ ์ํ ์ ์๋ค.
Array ์์ฑ์ ํจ์๋ก ๋ง๋ ๋ชจ๋ ๋ฐฐ์ด ๊ฐ์ฒด์ random() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋๋ก, ํจ์์์๋ arr ๋์ this
๋ผ๊ณ ์จ์ค์ผ ํ๋ค.