๐ก ํ๋กํ ํ์
JavaScript์์ ์์์ ์ํด ์ฌ์ฉํ๋ ๋งค์ปค๋์ฆ
ํด๋์ค
JavaScript์๋ class๊ฐ ์๊ธฐ ๋๋ฌธ์ ์์ฑ์ ํจ์๋ฅผ ์ฌ์ฉํด์ ๊ทธ ์ญํ ์ ๋์ ํฉ๋๋ค.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(this.name + " said hello");
}
}
}
new ํค์๋๋ฅผ ์ด์ฉํด Human์์ฑ์ ํจ์๋ฅผ ์คํํ๊ณ ์ ๋ฌ ์ธ์๋ก name๊ณผ age๋ฅผ ์ค๋๋ค.
let steve = new Human('steve', 30);
steve.sayHello(); // "steve said hello"
let kim = new Human("kim", 25);
kim.sayHello(); // "kim said hello"
์ด๋ ๊ฒ ๋ง๋ ์ธ์คํด์ค ๊ฐ์ฒด๋ค์ ๊ณตํต์ ์ผ๋ก ๋ถ๋ชจ์ ๋ฉ์๋๋ฅผ ์์ ๋ฐ์์ ์ฌ์ฉ ๊ฐ๋ฅํฉ๋๋ค.
์์๋ฐ์ ์์ฑ๊ณผ ๋ฉ์๋๋ ์์ ๊ฐ์ฒด๊ฐ ์ง์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
๊ทธ๋ฐ๋ฐ ์ธ์คํด์ค๊ฐ ๋ง๋ค์ด์ง๋ฉด์ ์๋์ผ๋ก [Prototype]์ด๋ผ๋ ๊ฐ์ฒด๊ฐ ๋ง๋ค์ด์ก์ต๋๋ค. ์ด๊ฒ ๋ญ๊น์?
ํ๋กํ ํ์
๋๊ฐ์ ๋ฉ์๋๋ฅผ ๊ตณ์ด ๋ชจ๋ ์์ ๊ฐ์ฒด๋ค์ด ๊ฐ์ง๊ณ ์์ ํ์๋ ์์ต๋๋ค.
๋ถํ์ํ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ญ๋นํ์ง ์๊ธฐ ์ํด ๋ถ๋ชจ ๊ฐ์ฒด(์์ฑ์)๋ง ๊ฐ์ง๊ณ ์๊ณ ์์๋ค์ ๊ทธ๊ฒ์ ์ฐธ์กฐ, ์กฐํํด์ ๊ฐ์ ธ๋ค ์ฐ๋ ํธ์ด ๋ ์ข์ต๋๋ค. ์ด๊ฒ์ ์ํด ํ๋กํ ํ์ ์ ์ฌ์ฉํฉ๋๋ค.
Human์ ํ๋กํ ํ์ ๊ฐ์ฒด์ ๋ฉ์๋๋ฅผ ๋ฃ์ด๋๋ฉด Human์์ฑ์๋ก ๋ง๋ ๋ชจ๋ ๊ฐ์ฒด๋ค์ ํด๋น ๋ฉ์๋๋ฅผ ์ง์ ๊ฐ์ง๊ณ ์์ง ์์๋ ์ฌ์ฉ ๊ฐ๋ฅํฉ๋๋ค.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
this.sayHello = function() {
console.log(this.name + " said hello");
}
}
sleep() {
console.log(`${this.name}์ ์ ์ ๋ค์์ต๋๋ค`);
}
}
sleep๋ฉ์๋๋ sayHello์ ๋ฌ๋ฆฌ prototype์ ๋ฃ์์ต๋๋ค.
let steve = new Human('steve', 30);
steve์ธ์คํด์ค๋ฅผ ์์ฑํ๊ณ ์ฝ์์ ์ฐ์ด๋ณด๋ฉด ๋ค์๊ณผ ๊ฐ์ด ๋์ต๋๋ค.
sayHello์ ๋ฌ๋ฆฌ sleep์ ํ๋กํ ํ์ ๊ฐ์ฒด ์์ ๋ค์ด์์ต๋๋ค.
ํ๋กํ ํ์ ๊ตฌ์กฐ๋
๊ฐ์ฒด ๊ฐ์ ๊ด๊ณ๋ฅผ ๊ตฌ์กฐํ์ํค๋ฉด ๋ค์๊ณผ ๊ฐ์ ๊ทธ๋ฆผ์ด ๋์ต๋๋ค.
Human ๊ฐ์ฒด์ prototype ํ๋กํผํฐ๋ Human์ prototype ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํค๊ณ prototype ๊ฐ์ฒด๋ constructor๋ผ๋ ํ๋กํผํฐ๋ฅผ ์์ฑํด Human ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
steve ๊ฐ์ฒด๊ฐ ์์ฑ๋ ๋ __proto__ํ๋กํผํฐ๊ฐ ๊ฐ์ด ์์ฑ๋ฉ๋๋ค. __proto__๋ Human์ prototype ๊ฐ์ฒด๋ฅผ ๊ฐ๋ฆฌํต๋๋ค.
๊ทธ๋ ๊ธฐ ๋๋ฌธ์ Human.prototype์ผ๋ก Human์ prototype ๊ฐ์ฒด์ ์ ๊ทผํ ์ ์๊ณ , steve.__proto__๋ฅผ ํตํด์๋ Human์ prototype ๊ฐ์ฒด์ ์ ๊ทผ์ด ๊ฐ๋ฅํฉ๋๋ค.
์ด๋ ๊ฒ ์๋ก๊ฐ ์๋ก๋ฅผ ๊ฐ๋ฆฌํค๋ ํน์ฑ์ผ๋ก ์ธํด์ ๋ค์๊ณผ ๊ฐ์ ์์ด ์ฑ๋ฆฝํฉ๋๋ค.
Human.prototype.constructor === Human;
Human.prototype === steve.__proto__;
Human.prototype.sleep === steve.sleep;
๋ ํผ๋ฐ์ค
- ์ฝ๋์คํ ์ด์ธ
- https://www.zerocho.com/category/JavaScript/post/573c2acf91575c17008ad2fc
- https://velog.io/@h0ngwon/Javascript-proto-vs-prototype-%EC%B0%A8%EC%9D%B4
- https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes