티스토리 뷰

이 페이지는 Pass By Value와 Pass By Reference를 설명하고 있다.

 

 

# pass vs call

Call By Value, Call By Reference 와 무슨 차이가 있을까?
보통 주어가 함수일 때 call by, 인수일 때 pass by를 사용하는 듯 하다.
> They are synonymous. The term 'call-by-value' means exactly the same as 'pass-by-value'.

 


# Pass By Value (Call By Value, 값에 의한 호출)

: 인자로 넘기는 값을 복사해서 새로운 함수에 전달하는 방식. 
값에 의한 호출은 원본값이 변경될 가능성은 없지만, 고비용과 메모리의 문제점이 있다.

예제1.

const a = 1; 
const b = a; 

console.log(a, b);    // 1  1 
console.log(a === b); // true 

a = 10; 
console.log(a, b);    // 1  10 
console.log(a === b); // false 

변수 a는 원시 타입인 숫자 타입 1을 저장하고 있다. 원시 타입의 경우 값이 복사되어 변수에 저장된다. 즉, 참조 타입으로 저장되는 것이 아니라 값 자체가 저장되게 된다.

변수 b에 변수 a를 할당할 경우, 변수 a의 값 1은 복사되어 변수 b에 저장된다.


예제2.

const callByValue = (varOne, varTwo) => {  
  console.log('Inside Call by Value Method');  
  const one = 100;  
  const two = 200;  
  console.log('varOne =' + varOne + 'varTwo =' + varTwo);  
}  
let varOne = 10;  
let varTwo = 20;  
console.log('Before Call by Value Method');  
console.log('varOne =' + varOne + 'varTwo =' +varTwo);  
callByValue(varOne, varTwo)
console.log('After Call by Value Method');  
console.log('varOne =' + varOne + 'varTwo =' + varTwo);  

output :  
———————  
Before Call by Value Method  
varOne =10 varTwo =20  
Inside Call by Value Method  
varOne =100 varTwo =200  
After Call by Value Method  
varOne =10 varTwo =20 

 


# Pass By Reference (Call By Reference, 참조에 의한 호출)

: 주소값을 인자로 전달하는 방식.
참조에 의한 호출은 원본값의 변경이 일어날 수도 있다는 문제점이 있다.


예제1.

const bar = foo; 
console.log(foo.val, bar.val); // 10 10 
console.log(foo === bar);      // true 

bar.val = 20; 
console.log(foo.val, bar.val); // 20 20 
console.log(foo === bar);      // true

foo는 객체를 저장하고 있는 것이 아니라 생성된 객체의 참조값 주소를 저장하고 있다.


예제2.

const callByReference = (varObj) => {  
  console.log('Inside Call by Reference Method');  
  varObj.a = 100;  
  console.log(varObj);  
}  
let varObj = { a: 1 }; 
console.log('Before Call by Reference Method');  
console.log(varObj); 
callByReference(varObj)  
console.log('After Call by Reference Method');  
console.log(varObj); 

output will be :  
———————  
Before Call by Reference Method  
{ a: 1 }  
Inside Call by Reference Method  
{ a: 100 }  
After Call by Reference Method  
{ a: 100 }
댓글
최근에 올라온 글
«   2024/11   »
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
Total
Today
Yesterday