๐Ÿ“Œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ํ…œํ”Œ๋ฆฟ(ํ‹€)

๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ(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