call by value, call by reference, call by sharing

call by value, call by reference, call by sharing ๋“ค์€ ์ธ์ž์™€ ๋งค๊ฐœ๋ณ€์ˆ˜ ๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

  1. call by value

์›์‹œ๊ฐ’์€ ๋ณต์‚ฌ๊ฐ€ ๋˜์„œ ๋งค๊ฐœ๋ณ€์ˆ˜์— ๋“ค์–ด๊ฐ„๋‹ค.

function func(arg) {
    console.log(arg);
}
func(5);

์•„๋ž˜์˜ ์ฝ”๋“œ๋Š” ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ๊ฐ์ฒด๋ฅผ ์ „๋‹ฌํ–ˆ์„ ๋•Œ ํ•จ์ˆ˜ ๋‚ด์˜ ์ฝ”๋“œ์— ์˜ํ•ด ์›๋ž˜ ์ธ์ž ๊ฐ’๋„ ๋ฐ”๋€” ์ˆ˜ ์žˆ๋‹ค.

function func(arg) {
    arg.a = 10;
    console.log(arg);
}
var data = {a:5};
func(data);

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์—์„œ๋Š” ํฌ์ธํ„ฐ ๊ฐ™์€ call by reference๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค! ๊ฐ์ฒด ์†์„ฑ์„ ์ˆ˜์ •ํ•  ๋•Œ๋Š” ์ฐธ์กฐ์ด์ง€๋งŒ, ๊ฐ์ฒด ์ž์ฒด๋ฅผ ์ˆ˜์ •ํ•  ๋•Œ๋Š” ๊ด€๊ณ„๊ฐ€ ๊นจ์ง„๋‹ค. ์ด๋ฅผ call by sharing์ด๋ผ๊ณ ๋„ ํ•œ๋‹ค. ์•„๋ž˜์˜ ์ฝ”๋“œ๋Š” call by reference๊ฐ€ ์•„๋‹ˆ๋ผ๋Š” ๊ฒƒ์„ ๋ณด์—ฌ์ค€๋‹ค.

function func(arg) {
    arg = 8;
    console.log(arg);
}
var data = {a:5};
func(data);
console.log(data);//{a:5}

Last updated