PracticeEveryday
Call by value vs Call by reference 본문
Call by ~~
=> 평가 전략(Evaluation Strategy) 중에 하나이며
프로그래밍 언어에서 함수 호출의 아규먼트(argument)의 순서를 언제 결정하고 함수에 어떤 종류의 값을 통과시킬지 결정하는 것
즉 함수에 인자로 어떤 걸 주느냐에 따라 함수가 어떻게 실행될지에 대한 방법을 결정하는 것이다.
parameter vs arguments parameter : 매개 변수(媒介變數) argument : 논거 주장 뜻 (인자)
parameter 는 formal parameter(형식 매개변수)이며 arguments는 actual parameter(실제 인자)이다.
let a = 1;
let func = function(b) { // parameter, formal parameter, 매개변수, 형식 매개변수
// code...
};
func(a); // arguments, actual parameter, 인자, 실인자
b : 매개변수 형식 매개변수 // parameter, formal parameter
1(a) : 인자, 실인자,// arguments, actual parameter
parameter는 함수 선언부에 정의되고 arguments는 ㅎ마수 호출부에서 정의된다!!
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.
let a = 1;
let func = function(b) { // callee
// 이 안에서 전달받은 b를 아무리 변형해도 밖의 a = 1 에는 변함이 없다!!
b = b + 1;
}
func(a); // caller
console.log(a); // 1
arguments로 값이 넘어온다. => 값이 넘어올 때 복사된 값이 넘어온다.
=> caller(호출하는 녀석)가 복사해서 넘겨 줬으므로 calle(호출 당한 녀석)에서 해당 인자를 지지고 볶아도 caller는 영향을 받지 않는다.
※ 기본적으로 자바스크립트는 원시값을 argumetns(인자)로 넘기면
call by value의 형태이기에 함수 내에서 아무리 변형해도 결과 적으로 넘긴 값은 원래 값이 찍히게 된다.
Call by reference // reference : 참조 참조에 의한 평가 전략
위키피디아
Call by reference (also referred to as pass by reference) is an evaluation strategy where a function receives an implicit reference to a variable used as argument,
rather than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable used as argument—something that will be seen by its caller.
Call by reference can therefore be used to provide an additional channel of communication between the called function and the calling function.
A call-by-reference language makes it more difficult for a programmer to track the effects of a function call,
and may introduce subtle bugs.
let a = {};
let func = function(b) { // callee
// 객체는 call by reference!! 안에 프로퍼티 값이 바뀐다 !!
b.a = 1;
}
func(a); // caller
console.log(a.a); // 1
arguments로 **reference(값에 대한 참조 주소, 메모리 주소를 담고 있는 변수)를 넘겨준다.
=> reference를 넘기니 해당 reference가 가리키는 값을 복사하지 않는다.
3. caller(호출하는 녀석)가 인자를 복사해서 넘기지 않았으므로 callee(호출 당한 녀석)에서 해당 인자를 지지고 볶으면 caller는 영향을 받는다.
Call by sharing
var a = {};
var func = function(b) { // callee
b = 1;
}
func(a); // caller
console.log(a); // {}
참조 타입을 넘겼는데 값이 변하지 않았다.
바로 자바스크립트에서는 무조건 call by value로 작동하기 때문이다.
사람들이 참조 타입을 넘기면 call by reference로 작동한다고 알고 있고, 위 코드가 그 생각이 오해임을 명백하게 밝혀주고 있다.
자바스크립트(자바, 루비, 파이썬 등등도 마찬가지…)에서는 참조 타입을 인자로 넘기면 참조값에 대한 복사본을 만들어서 넘긴다.
Call by sharing
1. 메모리 주소 임의 지정
변수 a에 담기는 것은 객체 {}가 담겨 있는 메모리 주소 0x12이다 (원시 값이 아닌 참조 타입!!)
함수에 참조 타입 객체를 넘겨주게 되면 a의 0x12를 복사해 0x12를 담고 있는 b를 만들어 전달하게 된다.
이떄 b도 0x12에 들어 있는 객체 {}를 가리키게 된다.
하지만 b =1 대입 연산자로 참조 값을 재할당 하기 때문에 기존에 참조하던 0x12 {}에서 0x13 1로 참조 대상이 변경 되었다.
그러므로 a의 {} 값은 변하지 않았따!!
- 자바스크립트에서 call by reference는 존재하지 않고 call by value만 존재한다.
- 참조 타입을 인자로 넘기면 참조값에 대한 복사본이 넘어간다.
- 이러한 혼동을 줄이고자 call by sharing이란 용어로 부르기도 한다.
(자알쓰) call by value vs call by reference
자알쓰란?자바스크립트 알고 쓰자. (잘 쓰자는 의미도 담겨있다.)자바스크립트라는 언어 자체는 내 기준에서는 설계 상 미스가 참 많다.함수 단위의 스코프, 호이스팅, 동적 타입 등등자바와 같
perfectacle.github.io
'정리 > Question' 카테고리의 다른 글
Joi (0) | 2022.05.13 |
---|---|
자료구조? 알고리즘? 추상 자료형? (0) | 2022.05.09 |
prototype vs __proto__ (0) | 2022.05.04 |
런타임 vs 컴파일 (0) | 2022.05.02 |
--dev, --save, --save-dev? (0) | 2022.05.01 |