๐ ๊ฐ์ฒด๋ฅผ ์์ฑํ ์ ์๋ ํ ํ๋ฆฟ(ํ)
๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ(Object-Oriented Programming)
๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ์์๋ prototype์ ๊ธฐ๋ฐ์ผ๋ก ๊ฐ์ฒด๋ฅผ ๋ง๋ค์์ง๋ง,
ES6๋ฌธ๋ฒ ์ดํ class๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ์ ํ ์ ์๋ค.
ํด๋์ค๊ฐ ํ๋กํ ํ์ ๋ณด๋ค ๊ฐํธํ๋ค.
๐

ํด๋์ค๋ฅผ ํตํด ๊ฐ์ฒด๋ฅผ ๋ง๋ค ์ ์๊ณ , ๊ทธ ๊ฐ์ฒด๋ฅผ ์ธ์คํด์ค๋ผ๊ณ ํ๋ค.
<aside> ๐ Class๋ ๊ฐ์ฒด์งํฅ ํ๋ก๊ทธ๋๋ฐ์์ ํน์ ๊ฐ์ฒด(์ธ์คํด์ค)๋ฅผ ์์ฑํ๊ธฐ ์ํ ๋ณ์์ ๋ฉ์๋(ํจ์)๋ฅผ ์ ์ํ๋ ์ผ์ข ์ ํ์ด๋ค.
</aside>
๐ย ๊ธฐ๋ณธย ํํ
//Class Keyword
class Group {
name = '๋ํ';
year = 2019;
}
const daepa = new Group();
console.log("daepa: ", daepa);
//Group { name: '๋ํ', year: 2019 }
class Dog {
//ํ๋กํผํฐ(์์ฑ)
//name;
//year;
constructor(name, year) {
//this๋ ํ์ฌ ์ธ์คํด์ค๋ฅผ ๋งํ๋ค.
this.name = name;
this.year = year;
}
}
ํ๋กํผํฐ๋ฅผ ๋ฏธ๋ฆฌ ์ ์ํ์ง ์๊ณ , constructor๋ง์ผ๋ก๋ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค!
โ๏ธย constructor - ์์ฑ์
//constructor - ์์ฑ์
// ํจ์์์์ ํ๋ผ๋ฏธํฐ์ ๋น์ทํ ์ญํ์ ํ๋ค.
class Dog {
//ํ๋กํผํฐ(์์ฑ)
name;
year;
constructor(name, year) {
//this๋ ํ์ฌ ์ธ์คํด์ค๋ฅผ ๋งํ๋ค.
this.name = name;
this.year = year;
}
}
โ๏ธย ์ธ์คํด์ค
new ํค์๋๋ฅผ ํตํด์ ๋ง๋ ๊ฐ์ฒด ํ๋ํ๋๋ฅผ ์ธ์คํด์ค๋ผ๊ณ ๋ถ๋ฅธ๋ค.
//์ธ์คํด์ค
const bom = new Dog();
console.log("bom: ", bom);
//Dog {name: undefined, year: undefined}
//์ธ์คํด์ค
const sangchu = new Dog("์์ถ", 2010);
console.log("sangchu: ", sangchu);
//Dog {name: '์์ถ', year: 2010}
console.log(sangchu.name);
//์์ถ
console.log(sangchu.year);
//2010