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

JS_๊ธฐ๋ณธ ๋ฌธ๋ฒ• (16)_์›์‹œํƒ€์ž…๊ณผ ์ฐธ์กฐํƒ€์ž…

by KASSID 2023. 3. 1.

๋ชฉ์ฐจ

    728x90

    JS์—๋Š” ์›์‹œํƒ€์ž…๊ณผ ์ฐธ์กฐํƒ€์ž…์ด ์กด์žฌํ•œ๋‹ค.

    ๊ทธ ๋‘˜์„ ๊ฐ’์˜ ๋ณต์‚ฌ์˜ ์ธก๋ฉด์—์„œ ๋น„๊ตํ•˜๋ฉฐ ์•Œ์•„๋ณด์ž!

     

    1) ์›์‹œํƒ€์ž…

    ์›์‹œํƒ€์ž…์€ ๊ฐ’์— ์˜ํ•œ ๋ณต์‚ฌ๊ฐ€ ์ด๋ฃจ์–ด์ง„๋‹ค.(Copy by value)

    let n1 = 1;
    let s1 = 'A';
    
    //n1, s1 ๋ณต์‚ฌ
    let n2 = n1;
    let s2 = s1;
    
    //์ƒˆ๋กœ์šด ๊ฐ’ ํ• ๋‹น
    n2 = 2;
    s2 = 'B';
    
    console.log(n1, s1);
    console.log(n2, s2);
    
    >>> 1 'A'
    >>> 2 'B'

    ์œ„์˜ ๊ฒฐ๊ณผ์ฒ˜๋Ÿผ ๊ฐ’ ์ž์ฒด๋ฅผ ๋ณต์‚ฌํ•˜๋Š” ๊ฒƒ์ด๋ฏ€๋กœ

    ๋ณต์‚ฌ๋ฅผ ํ•œ ์ดํ›„, ๋ฌด์Šจ ์ง“์„ ํ•˜๋“  ์„œ๋กœ์—๊ฒŒ ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š๋Š”๋‹ค.

     

    2) ์ฐธ์กฐํƒ€์ž…

    ์ฐธ์กฐํƒ€์ž…์€ '์ฃผ์†Œ๊ฐ’'์ด ๋ณต์‚ฌ๊ฐ€ ๋œ๋‹ค. (Copy by reference)

    const ob1 = {
    	num : 1, str : 'A'
    };
    
    //๋ณต์‚ฌ
    const ob2 = ob1;

     

    ob2 = {};
    
    >>> Uncaught TypeError: Assignment to constant variable.

     

    ์ƒ์ˆ˜๋กœ ์„ ์–ธํ•˜์˜€๊ธฐ ๋•Œ๋ฌธ์— ob2์— ์ƒˆ๋กœ์šด ๊ฐ์ฒด๋ฅผ ํ• ๋‹นํ•  ๊ฒฝ์šฐ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค!

     

    console.log(ob1);
    console.log(ob2);
    
    >>> {num: 1, str: 'A'}
    >>> {num: 1, str: 'A'}

    ์œ„์ฒ˜๋Ÿผ ๋˜‘๊ฐ™์ด ๋ณต์‚ฌ๊ฐ€ ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•  ์ ์€ ๊ฐ์ฒด๋Š” cosnt๋กœ ์„ ์–ธํ–ˆ์Œ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ 

    ๋‚ด๋ถ€ ๊ฐ’์€ ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.(C,U,D ๋ชจ๋‘ ๊ฐ€๋Šฅ)

    //๋‚ด๋ถ€ ๊ฐ’ ๋ณ€๊ฒฝ
    ob2.num = 2;
    ob2.str = 'B';
    
    console.log(ob1);
    console.log(ob2);
    
    >>> {num: 2, str: 'B'} //ob1๋„ ํ•จ๊ป˜ ๋ณ€๊ฒฝ๋จ
    >>> {num: 2, str: 'B'}

    ์œ„์˜ ๊ฒฐ๊ณผ์ฒ˜๋Ÿผ ๋‚ด๋ถ€ ๊ฐ’์˜ ๋ณ€๊ฒฝ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

    ๋˜ํ•œ ob2๋งŒ์„ ๋ณ€๊ฒฝํ–ˆ์Œ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ  ob1๊นŒ์ง€ ํ•จ๊ป˜ ๋ณ€๊ฒฝ๋˜์—ˆ์Œ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.

     

    ์ด๋Š” ob1์„ ๋ณต์‚ฌํ•  ๋•Œ ๋‚ด๋ถ€์˜ ๊ฐ’ ์ž์ฒด๋ฅผ ๋ณต์‚ฌํ•˜๋Š” ๊ฒƒ์ด ์•„๋‹Œ

    ๋‚ด๋ถ€์˜ ๊ฐ’์ด ๋“ค์–ด์žˆ๋Š” ํž™ ๋ฉ”๋ชจ๋ฆฌ์˜ ์ฃผ์†Œ๋ฅผ ๋ณต์‚ฌํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

     

    ์ฆ‰, ob1๊ณผ ob2๊ฐ€ ์„œ๋กœ ๊ฐ™์€ ์ฃผ๋จธ๋‹ˆ๋ฅผ ๊ณต์œ ํ•˜๊ฒŒ ๋˜๋Š” ๊ฒƒ์ด๋‹ค.

     

    ๋Œ“๊ธ€