๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐ŸŒŒ | WEB DEV/Vanilla JS

JS_๊ธฐ๋ณธ ๋ฌธ๋ฒ• (33)_ constructor ๋ฌธ๋ฒ•

by KASSID 2023. 8. 8.

๋ชฉ์ฐจ

    728x90

    JS์˜ Object๋ฅผ ์ƒ์„ฑํ•˜๋Š” constructor ๋ฌธ๋ฒ•์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด์ž.

     

    0. Object์˜ ๋ณต์‚ฌ ๋ฌธ์ œ

    Object๋Š” Reference ๋ฐ์ดํ„ฐ ํƒ€์ž…์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ณต์‚ฌ๋ฅผ ํ• ๋•Œ ์•„๋ž˜์™€ ๊ฐ™์ด ๋‹จ์ˆœํ•˜๊ฒŒ ์ง„ํ–‰ํ•ด์„œ๋Š” ์•ˆ๋œ๋‹ค.

     

    ์ž˜๋ชป๋œ ๊ฐ์ฒด ๋ณต์‚ฌ ์˜ˆ์‹œ

    let obj1 = {name: "Kassid"};
    let obj2 = obj1;

     

    ์ด๋ ‡๊ฒŒ ๋ณต์‚ฌ๋ฅผ ํ•˜๊ฒŒ ๋œ๋‹ค๋ฉด ๊ฐ’ ์ž์ฒด์˜ ๋ณต์‚ฌ๊ฐ€ ์•„๋‹Œ ๋ ˆํผ๋Ÿฐ์Šค๋ฅผ ๋ณต์‚ฌํ•˜๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— 

    ์•ˆ์ „ํ•œ ๋ณต์‚ฌ๋ผ๊ณ  ํ•  ์ˆ˜ ์—†๋‹ค.

     

     

    1. constructor ๋ฌธ๋ฒ•

    constructor๋Š” ์œ„์˜ object๋ฅผ ์ƒ์„ฑ๊ธฐ๊ณ„๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ ์ด์šฉํ•ด ์œ„์˜ ๋ณต์‚ฌ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    ์ด๋ฅผ ์ด์šฉํ•ด์„œ ๋น„์Šทํ•œ ๊ฐ์ฒด๋ฅผ ์†์‰ฝ๊ฒŒ ์–‘์‚ฐํ•ด๋‚ผ ์ˆ˜ ์žˆ๋‹ค.

     

    ์‚ฌ์šฉ๋ฒ•

    function ์ƒ์‚ฐ๊ธฐ๊ณ„๋ช…(){
       this.์†์„ฑ = ...;
       ...
    }

     

    constructor ๋ฌธ๋ฒ•์€ ์ด์ฒ˜๋Ÿผ function ํ‚ค์›Œ๋“œ๋ฅผ ์ด์šฉํ•œ๋‹ค.

    ๋˜ํ•œ ๊ฐ ์ธ์Šคํ„ด์Šค์˜ ์†์„ฑ๋“ค์„ this. ~ ์œผ๋กœ ์ง€์ •ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

     

     

     

    ์˜ˆ์‹œ 1. ๋ณต์‚ฌ

    function Student(){
      this.name = "Kassid";
      this.code = "1";
    }
    
    let ํ•™์ƒ1 = new Student();
    let ํ•™์ƒ2 = new Student();
    
    console.log(ํ•™์ƒ1, ํ•™์ƒ2);

     

     

    this.~ ์— ๊ฐ’์„ ์ง€์ • ํ•˜๋ฉด ์ด์ฒ˜๋Ÿผ ๋ณต์‚ฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค.

     

     

    ์˜ˆ์‹œ 2. ์–‘์‚ฐ

    function Student(name, code){
      this.name = name;
      this.code = code;
    }
    
    let ํ•™์ƒ1 = new Student("Kassid", 1);
    let ํ•™์ƒ2 = new Student("David", 2);
    
    console.log(ํ•™์ƒ1, ํ•™์ƒ2);

     

     

    ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ด์šฉํ•ด ์ธ์Šคํ„ด์Šค๋งˆ๋‹ค ์†์„ฑ๋“ค์„ ๋‹ค๋ฅด๊ฒŒ ์ ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

    ๋ฌผ๋ก  ๊ธฐ๋ณธ๊ฐ’์„ ์ง€์ •ํ•ด์ฃผ๋Š” ๊ฒƒ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค.

     

     

    ๋Œ“๊ธ€