Notice
Recent Posts
Recent Comments
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

MJ.Story

call by value vs call by reference 본문

IT/Javascript

call by value vs call by reference

아토씌 2022. 11. 22. 00:44

call by value

위키피디아에서는 call by value를 다음과 같이 설명하고 있다.

Call by value (also referred to as pass by value) is the most common evaluation strategy,used in languages as different as C and Scheme. In call by value,the argument expression is evaluated,and the resulting value is bound to the corresponding variable in the function(frequently by copying the value into a new memory region).If the function or procedure is able to assign values to its parameters,only its local copy is assigned—that is,anything passed into a function call is unchanged in the caller’s scope when the function returns.

영어가 잘 안 되니 대충 call by value의 설명을 요약해보자면 다음과 같다.

  1. arguments로 이 넘어온다.
  2. 값이 넘어올 때 복사된 값이 넘어온다.
  3. caller(호출하는 녀석)가 인자를 복사해서 넘겨줬으므로 callee(호출당한 녀석)에서 해당 인자를 지지고 볶아도 caller는 영향을 받지 않는다.

간단한 예제로 살펴보자

var a = 1;
var func = function(b) { // callee
b = b + 1;
}
func(a); // caller
console.log(a); // 1

기본적으로 자바스크립트는 원시값을 arguments로 넘겨주면 call by value의 형태로 작동한다.따라서 caller가 1을 arguments로 넘겨줘도 그 값은 복사되어 넘어오기 때문에 callee 내부에서 지지고 볶고 해도 전혀 영향을 받지 않아서 결과적으로 a 값은 원래 값인 1이 찍히게 된다.

call by reference

위키피디아에서는 call by reference를 다음과 같이 설명하고 있다.

역시나 영어가 부족하니 대충 call by reference를 요약해보자면 다음과 같다.

  1. arguments로 **reference(값에 대한 참조 주소, 메모리 주소를 담고있는 변수)**를 넘겨준다.
  2. reference를 넘기다 보니 해당 reference가 가리기는 값을 복사하지는 않는다.
  3. caller(호출하는 녀석)가 인자를 복사해서 넘기지 않았으므로 callee(호출당한 녀석)에서 해당 인자를 지지고 볶으면 caller는 영향을 받는다.

기본적으로 자바스크립트는 참조 타입을 arguments로 넘겨주면 call by reference의 형태로 작동한다. 따라서 caller가 객체 a를 parameter로 넘겼을 때 실제 argument로 넘어오는 값은 객체 a에 대한 reference이지 복새된 객체 a가 아니다.

따라서 callee 내부에서 지지고 뽁고 하면 영향을 받기 때문에 조심해서 사용해야 한다. 라고 오해하고있다.

 

출처 https://perfectacle.github.io/2017/10/30/js-014-call-by-value-vs-call-by-reference/