Prototype in Javascript - seowonintech/react-native-todo-list GitHub Wiki
์ด ํ๋กํ ํ์
๊ธฐ๋ฐ ํ๋ก๊ทธ๋๋ฐ์ Class ๊ธฐ๋ฐ OOP ์ธ์ด๋ฅผ ๋ค๋ฃจ๋ ์ฌ๋์๊ฒ๋ ์ดํด๊ฐ ์ ์๊ฐ๋ ๋ถ๋ถ ์ผ์๋ ์๋ค. Class ๊ธฐ๋ฐ์ ์ธ์ด์์๋ Class ์์ ๊ธฐ์ ๋ ๋ด์ฉ์ ๊ธฐ๋ฐ์ผ๋ก ์ธ์คํด์ค๋ฅผ ์์ฑํ์ฌ ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ๋ค. ํ์ง๋ง ์๋ฐ์คํฌ๋ฆฝํธ๋ Class ๊ฐ ์กด์ฌํ์ง ์๋๋ค. ๊ทธ๋์ ์๋ฐ์คํฌ๋ฆฝํธ์์๋ ๊ฐ์ฒด์ ์ํ์ธ ํ๋กํ ํ์
์ ์ด์ฉํ ํด๋ก๋(Cloning: ๋ณต์ฌ)๊ณผ ๊ฐ์ฒดํน์ฑ์ ํ์ฅํด ๋๊ฐ๋ ๋ฐฉ์์ ํตํด ์๋ก์ด ๊ฐ์ฒด๋ฅผ ์์ฑํด ๋ธ๋ค.
- Prototype์ด๋ผ๋ ์ฉ์ด๋ ๋๊ฐ์ง๋ก ๋๋๋ค.
- Prototype Property
- Prototype Link
Prototype Property : Prototype object. ์๊ธฐ ์์ ์ Cloneํ๋ ๊ฐ์ฒด๋ค์ด ๊ฐ์ง๊ฒ๋ ์์ฑ๋ค (์๊ธฐ ์์ ์ ๋ณต์ฌ๋ณธ???)
Prototype Link : ์๊ธฐ ์์ ์ ๋ง๋ค์ด๋ธ ๊ฐ์ฒด์ ์ํ
์ด๋ ํ ๊ฐ์ฒด๊ฐ ๋ง๋ค์ด์ง๊ธฐ ์ํด ๊ทธ ๊ฐ์ฒด์ ๋ชจํ๊ฐ ๋๋ ๋
์์ ํ๋กํ ํ์
์ด๋ผ๊ณ ํ๋ค. Java๋ php์์ ๋งํ๋ class๊ฐ ๋ฐ๋ก ์๋ฐ์คํฌ๋ฆฝํธ์ ํ๋กํ ํ์
๊ณผ ๋์ผํ ์๋ฏธ์ผ ๊ฒ์ด๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์ ๋ชจ๋ ๊ฐ์ฒด๋ ์์ ์ ์์ฑํ ๊ฐ์ฒด ์ํ์ ๋ํ ์จ๊ฒจ์ง ์ฐ๊ฒฐ์ ๊ฐ๋๋ค. ์ด๋ ์๊ธฐ ์์ ์ ์์ฑํ๊ธฐ ์ํด ์ฌ์ฉ๋ ๊ฐ์ฒด์ํ์ ํ๋กํ ํ์ ์ด๋ ํ๋ค. ์๋ฐ์คํฌ๋ฆฝํธ์ ๋ชจ๋ ๊ฐ์ฒด๋ Object ๊ฐ์ฒด์ ํ๋กํ ํ์ ์ ๊ธฐ๋ฐ์ผ๋ก ํ์ฅ ๋์๊ธฐ๋๋ฌธ์ ์ด ์ฐ๊ฒฐ์ ๋์ Object ๊ฐ์ฒด์ ํ๋กํ ํ์ Object ๋ค.
function A() {};
var B = new A();๋ชจ๋ ํจ์ ๊ฐ์ฒด์ Constructor๋ prototype ์ด๋ ํ๋กํผํฐ๋ฅผ ๊ฐ์ง๊ณ ์๋ค. ์ด prototype ํ๋กํผํฐ๋ ๊ฐ์ฒด๊ฐ ์์ฑ๋ ๋น์ ๋ง๋ค์ด์ง๋ ๊ฐ์ฒด ์์ ์ ์ํ์ด๋ prototype ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํจ๋ค. ์ฆ ์์ ์ ๋ง๋ ์ํ์ด ์๋ ์์ ์ ํตํด ๋ง๋ค์ด์ง ๊ฐ์ฒด๋ค์ด ์ํ์ผ๋ก ์ฌ์ฉํ ๊ฐ์ฒด๋ฅผ ๋งํ๋ค. prototype object๋ default๋ก empty Object ๋ฅผ ๊ฐ๋ฆฌํจ๋ค.
์๋ฐ์คํฌ๋ฆฝํธ์ ๋ชจ๋ ๊ฐ์ฒด๋ ์์ฑ๊ณผ ๋์์ ์๊ธฐ์์ ์ด ์์ฑ๋ ๋น์์ ์ ๋ณด๋ฅผ ์ทจํ Prototype Object ๋ผ๋ ์๋ก์ด ๊ฐ์ฒด๋ฅผ Cloning ํ์ฌ ๋ง๋ค์ด๋ธ๋ค. ํ๋กํ ํ์ ์ด ๊ฐ์ฒด๋ฅผ ๋ง๋ค์ด๋ด๊ธฐ์ํ ์ํ์ด๋ผ๋ฉด ์ด Prototype Object ๋ ์๊ธฐ ์์ ์ ๋ถ์ ์ด๋ฉฐ ์์ ์ ์ํ์ผ๋ก ๋ง๋ค์ด์ง ๋ค๋ฅธ ๊ฐ์ฒด๊ฐ ์ฐธ์กฐํ ํ๋กํ ํ์ ์ด ๋๋ค. ์ฆ ๊ฐ์ฒด ์์ ์ ์ด์ฉํ ๋ค๋ฅธ ๊ฐ์ฒด๋ค์ด ํ๋กํ ํ์ ์ผ๋ก ์ฌ์ฉํ ๊ฐ์ฒด๊ฐ Prototype Object ์ธ ๊ฒ์ด๋ค. ์ฆ ์์์ ์ธ๊ธํ __proto__๋ผ๋ prototype ์ ๋ํ link๋ ์์์์ ๋ฌผ๋ ค๋ฐ์ ๊ฐ์ฒด์ ํ๋กํ ํ์ ์ ๋ํ ์ ๋ณด์ด๋ฉฐ prototype ํ๋กํผํฐ๋ ์์ ์ ์ํ์ผ๋ก ๋ง๋ค์ด์ง ์๋ก์ด ๊ฐ์ฒด๋ค ์ฆ ํ์๋ก ๋ฌผ๋ ค์ค ์ฐ๊ฒฐ์ ๋ํ ์์ฑ์ด๋ค.
//#์์ 1.
var A = function () {
this.x = function () {
//do something
};
};
//#์์ 2.
// ์ฌ๊ธฐ์ A.prototype์ Prototype Object๋ผ๊ณ ๋ถ๋ฅด๋ ๋ฏ
var A = function () { };
A.prototype.x = function () {
//do something
};prototype ํ๋กํผํฐ๋ Constructor๊ฐ ๊ฐ์ง๋ ํ๋กํผํฐ ์ด๋ค. ๊ทธ๋ฆฌ๊ณ *ํจ์๊ฐ์ฒด๋ง ์ด ํ๋กํผํฐ๋ฅผ ๊ฐ์ง๊ณ ์๋ค
// ์๊ธฐ ์์
var B = function A(){}
// var B = {} // syntax error
// var B = () => {} // syntax error
var C = new B();
console.log(B.__proto__); // [Function]
console.log(B.prototype); // A {}
console.log(C.prototype); // undefined