let's get IT with DAVINA ๐ป
Prototype ๋ณธ๋ฌธ
TypeScript๋ฅผ ๋ฐฐ์ฐ๋ฉด์ ๊ฒฐ๊ตญ, ํ์ ์คํฌ๋ฆฝํธ๋ ์๋ฐ์คํฌ๋ฆฝํธ์ superset์ธ๋ฐ ๊ทธ๋ฌ๋ ค๋ฉด JavaScript ๊ฐ๋ ์ ์กฐ๊ธ ๋ ์ ๋ฆฌ ํ ํ์์ฑ์ ๋๊ผ๋ค๋น
Prototype์ JS์ ์์ ๊ธฐ๋ฅ, ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ์ ์ํ ๊ฒ์ด๋ค!!!
Prototype
TS๋ ์๋์๊ฐ์ด JS์ superset์ ๋๋ค. JS์์ ์์๋, class, interface, generics, types ๋ฑ์ ์ด์ฉํด์ ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ์ด ๊ฐ๋ฅํ์ต๋๋ค.
BUT, JS๋ ์๋ฐํ ๋งํ๋ฉด proto-based๋ฅผ ํตํด ๊ฐ์ฒด ์งํฅ์ ๋๋ค.
๋ํ, ES6๋ถํฐ๋ class๋ฅผ ์ด์ฉํด์ ํ๋กํ ๋ฅผ ๊ธฐ๋ฐ์ด๊ธฐ ๋๋ฌธ์ ๊ฐ์ฒด ์งํฅ ํ๋ก๊ทธ๋๋ฐ์ด ๊ฐ๋ฅํฉ๋๋ค.
Prototype์ ์์์ ์ํด ์ฐ์ด๋ ์์ด์ ๋๋ค!
์ฐ๋ฆฌ๊ฐ Class๋ฅผ ์ด์ฉํด์ ์์์ ๊ตฌํํ ์ ์๋ ๊ฒ์ฒ๋ผ JS์์ Prototype์ ์ด์ฉํด์ ์์์ ๊ตฌํํ ์ ์์ต๋๋ค.
Prototype์ ์์ด ๋ป์, "์ถ์ํํด์ ๊ทธ๋ฆผ์ ๊ทธ๋ฆฌ๋ค"๋ ๋๋์ด๋ค.
So, How to ๊ตฌํ Proto?
const x = {};
const y = {};
console.log(x);
console.log(y);
console.log(x.toString());
console.log(x.__proto__ === y.__proto__);
const array = [];
console.log(array);
์์ ๊ฐ์ด, ๋น ๊ฐ์ฒด๋ ๋ฐฐ์ด์ด๋๋ผ๋ ๊ฐ๋ฐ์ ๋๊ตฌ๋ฅผ ์ผ์ ํ์ธํด๋ณด๋ฉด __Proto__ ์์ ์๋ ํจ์๋ค์ ์ฌ์ฉํ ์ ์๋ค.
๋ํ, array๋๋ผ๋ Object Proto๋ฅผ ๊ธฐ๋ณธ์ผ๋ก ์์๋ฐ๊ณ ์๋ ๊ฑธ ํ์ธํ ์ ์๋ค.
function CoffeeMachine(beans) {
this.beans = beans;
// Instance member level
/* this.makeCoffee = shots => {
console.log('making... โ๏ธ');
}; */
}
// Prototype member level
CoffeeMachine.prototype.makeCoffee = shots => {
console.log('making... โ๏ธ');
};
const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);
function LatteMachine(milk) {
this.milk = milk;
}
LatteMachine.prototype = Object.create(CoffeeMachine.prototype);
const latteMachine = new LatteMachine(123);
console.log(latteMachine);
latteMachine.makeCoffee();
- Instance member level์์๋ console.log(machine1)์ ํ๋ฉด {bean:10}์ ๊ฐ์ฒด && makeCoffee๋ผ๋ ํจ์ ๋ ๋ค ๋ฐ๋ก ๋ณด์ธ๋ค
- BUT, prototype member level์ฒ๋ผ ๊ตฌํํ๋ฉด makeCoffee๊ฐ ๋ฐ๋ก ๋ณด์ด๋๊ฒ ์๋๋ผ, __Proto__์์ ๋ค์ด๊ฐ๊ฒ ๋๋ค.
- ๋ํ, LatteMachine.prototype=Object.create(CoffeeMachine.prototype)์ ํตํด CoffeeMachine์ proto๋ฅผ LatteMachine๋ ์์ ๋ฐ์ ์ ์๋ค.
๋ฐ๋ผ์, Prototype-based Programming์ด๋?
- JS๊ฐ ๊ฐ์ฒด ์งํฅ์ ํ๋ก๊ทธ๋๋ฐ์ ํ ์ ์๋ ํ๋์ ๋ฐฉ๋ฒ (a style of OOP)
- behavior reuse ํ๋์ ์ฌ์ฌ์ฉ → ์์(inheritance)
- by reusing existing objects
- that serve as prototype
'DEV_IN > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Inside JavaScript] Chapter 1. ์๋ฐ์คํฌ๋ฆฝํธ ๊ธฐ๋ณธ ๊ฐ์ (0) | 2023.03.27 |
---|---|
Module (2) | 2023.02.28 |
This (6) | 2023.02.28 |
JavaScript Event Loop๋? (4) | 2023.02.22 |
priceFormatter (0) | 2023.02.08 |