October 22, 2021
์์์ ๊ฐ์ฒด๊ฐ ๋ค๋ฅธ ๊ฐ์ฒด์ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋๋ก ํ๋ OOP์ ํต์ฌ ๊ฐ๋
์ค ํ๋๋ค.
์์์ ์ด์ฉํ๋ฉด ์ ํ๋ฆฌ์ผ์ด์
์ ๋ค๋ฅธ ๋ถ๋ถ์์ ์ฝ๋๋ฅผ ์ฝ๊ฒ ์ฌ์ฌ์ฉํ ์ ์๋ค.
Bad Example
Circle Class๊ฐ ์๊ณ ์ด Class๋ computeOptimumLocation() ์ด๋ผ๋ ๋ฉ์๋๋ฅผ ๊ฐ์ง๋ค๊ณ ํ์.Square Class๊ฐ ์๊ณ ์ด Class๋ ๋ง์ฐฌ๊ฐ์ง๋ก computeOptimumLocation() ์ด๋ผ๋ ๋ฉ์๋๋ฅผ ๊ฐ์ง๋ค๊ณ ํ์.Circle Class์ Square Class๊ฐ ๋๊ฐ์ ์ญํ ์ ํ๋ ๋ฉ์๋๋ฅผ ๊ฐ๊ฐ ๋ฐ๋ก ๊ฐ์ง๊ณ ์๋ ์
์ด๋ค.computeOptimumLocation์ ๋ฒ๊ทธ๊ฐ ์๊ฑฐ๋ ์ฝ๋๋ฅผ ๊ฐ์ ํ๊ณ ์ถ์ผ๋ฉด ๋์ผํ ์ฝ๋๋ฅผ ์ฌ๋ฌ ๋ฒ ๋ณ๊ฒฝํด์ผ ํ๋ค.Good Example
Shape๋ผ๋ Class๋ฅผ ์์ฑํ๊ณ ์ด Class์ computeOptimumLocation() ์ด๋ผ๋ ๋ฉ์๋๋ฅผ ์ ์ํ๋ค.Circle, Square Class๊ฐ ์ด๋ฅผ ์์๋ฐ๋๋ก ํ๋ค.Shape Class๋ Base/Super/Parent Class ๋ก ์ฌ๊ธด๋ค.Circle, Square Class๋ Derived/Sub/Child Class๋ก ์ฌ๊ธด๋ค.example
computeOptimumLocation()example
let x = {}; ๋ฅผ ์ ์ธ,ํ ๋นํ ํ x ๋ฅผ ์ฐ์ด๋ณด๋ฉด __proto__ ์์ฑ์ ๊ฐ๊ณ ์๋ ๊ฒ์ ํ์ธํ ์ ์๋ค.__proto__ ๋ ์ฌ๋ฌ properties์ methods๋ฅผ ๊ฐ์ง๊ณ ์๋ค. ex) constructor, toStringx.__proto__.toString() ์ผ๋ก ์ ๊ทผํ ์ ์์ง๋ง, x.toString() ์ผ๋ก ๋ฐ๋ก ์ ๊ทผํ ์ ์๋ค.constructor ์์ฑ์ ์ ๊ทผํ ์ ์๊ฒ ๋๋ค. ์ด constructor์์ฑ์ ํด๋น ๊ฐ์ฒด๋ฅผ ์์ฑํ๋ ๋ฐ ์ฌ์ฉ๋ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.x ๊ฐ์ฒด๋ฅผ ๋ฉ๋ชจ๋ฆฌ์ ๊ฐ๊ณ ์๊ณ x ๊ฐ์ฒด๋ ๋ ๋ค๋ฅธ ๊ฐ์ฒด๋ฅผ ํฅํ ๋งํฌ๋ฅผ ๊ฐ๊ณ ์๋ค. ์ด๋ฅผ ํ๋กํ ํ์
์ด๋ผ ํ๋ค.x๋ ๋น ๊ฐ์ฒด์ธ๋ฐ ์ด๋ป๊ฒ x.toString() ๊ณผ ๊ฐ์ด ์ ๊ทผํ ์ ์์๊น?
x์ property์ method๋ฅผ ์ฐพ๋๋ค.x์ ํ๋กํ ํ์
์์ ์ฐพ๋๋ค.์๋ฐ์คํฌ๋ฆฝํธ์์์ ์์์ โ์ฐ๊ฒฐโ์ด๋ค
let person = { name: 'Jessie' };
console.log(person.toString()); // [object Object]
for (let key in person) {
console.log(key); // name
}
console.log(Object.keys(person)); // ["name"]person ์๋ ์์ฑ์ผ๋ก name๋ง ๊ฐ์ง๊ณ ์์ง๋ง, __proto__ ๋ฅผ ํตํด toString() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ์ ์๋ค.person์ด ๊ฐ์ง key๋ฅผ ์ถ๋ ฅํด๋ณด๋ฉด name ๋ง ์ถ๋ ฅ๋๋ค. ์ฌ๊ธฐ์๋ person์ด ์ง์ ์ ์ผ๋ก ๊ฐ์ง๊ณ ์๋ ์์ฑ๋ง ์ถ๋ ฅ๋๊ธฐ ๋๋ฌธ์ด๋ค.console.log(Object.keys(person)); ๋ ์ด์ ๋ง์ฐฌ๊ฐ์ง๋ก ์ง์ ์ ์ผ๋ก ๊ฐ์ง๊ณ ์๋ ์์ฑ๋ง ์ถ๋ ฅ๋์ด [โnameโ] ์ด ์ถ๋ ฅ๋๋ค.