본문 바로가기

javascript

[javascript] call by value, call by reference, call by sharing / 원시타입과 참조타입 / type of 와 instance of

call by value  vs  call by reference vs call by sharing

call by value  vs  call by reference 

 

함수의 매개변수를 값으로 전달하는 방식이 Call by Value이고 함수의 매개변수를 참조로 전달하는 방식이 Call by Reference 이다.

 

const flight = 'LH234';
const jane = {
  name: 'Jane Austin',
  passport: 2933621416 
  };
const checkIn = function (flightNum, passenger) {
  flightNum = 'LH999';
  passenger.name = 'Ms. ' + passenger.name;
  
  if (passenger.passport === 2933621416) {
    alert('Checked in');
  } else {
    alert('Wrong passport!');
  }
};
 checkIn(flight, jane);
 console.log(flight);  //LH234 출력됨(값이 변경되지 않음)  --> call by value
 console.log(jane);    //{ name: 'Ms.Jane Austin', passport: 2933621416} 출력됨(값이 변경됨)  --> call by reference


// 아래와 동일한 방식으로 볼 수 있다.
// const flightNum = flight;
// const passenger = jane;

//참조 : The Complete JavaScript Course (Udemy, Jonas Schmedtmann)

call by sharing

 

함수의 매개변수를 속성 공유로 전달하는 방식이 Call by Sharing이다. (정확하지 않을 수 있음) 참조로 전달하는 방식(Call by Reference)과 차이점은 함수 안에서 인자를 새로 할당했을 때 호출한 곳에서 접근할 수 없다는 점이다. 함수에 인자를 넘기면 값을 복사한 지역 변수로 사용하는데 객체 형태의 인자를 넘기면 속성은 공유하지만 속성은 새로운 메모리 주소를 사용하고 지역변수에는 변동이 없게 된다. 원본객체는 재할당되지 않게 된다. (정확하지 않을 수 있음)

 

const flight = 'LH234';
const jane = {
  name: 'Jane Austin',
  passport: 2933621416,
  ticket : 00000563
};
const checkIn = function (flightNum, passenger) {
  flightNum = 'LH999';
 //( passenger.name = 'Ms. ' + passenger.name;) //과 비교해보면 값이 다름
  passenger = {
  name: 'James Austin',
  passport: 2933621416,
  ticket : 00000003
  }
  if (passenger.passport === 2933621416) {
    alert('Checked in');
  } else {
    alert('Wrong passport!');
  }
};
checkIn(flight, jane);
console.log(flight); //LH234 출력됨(값이 변경되지 않음) ---> call by value
console.log(jane); //{ name: 'Jane Austin', passport: 2933621416, ticket : 00000563
                     } 출력됨(값이 변경되지 않음.) ---> call by sharing

 

 

 

출처: Tech Talk: Pass By Sharing with Javascript (Fullstack AcademyFullstack Academy) https://youtu.be/1YFss_4B_o4

 

 

 원시타입과 참조타입 

 

원시 타입 은 정수, 실수, 문자, 논리 리터럴등의 실제 데이터 값을 저장하는 타입이고, 참조 타입 은 객체(Object)의 번지를 참조(주소를 저장)하는 타입으로 메모리 번지 값을 통해 객체를 참조하는 타입이다.

  출처: Accelerated JavaScript Training Course (Udemy, Maximilian Schwarzmüller)

  var aNumber = 5;
  console.log(aNumber);
  var anotherNumber = aNumber;
  console.log(anotherNumber);
  aNumber = 12;
  console.log(aNumber);   //12 출력됨
  console.log(anotherNumber); //5 출력됨

출처: Accelerated JavaScript Training Course (Udemy, Maximilian Schwarzmüller)

var array = [1,2,3];
var anotherArray = array;
console.log(array);
console.log(anotherArray);

array.push(4);
console.log(array);        //[1,2,3,4] 출력됨.
console.log(anotherArray); //[1,2,3,4] 출력됨.

 

typeof 와 instanceof

 

typeof는 데이터 타입을 반환하는 비교 연산자이고 instanceof는  특정 클래스의 인스턴스인지 여부를 boolean값으로 반환하는 비교연산자이다.  typeof는 원시타입에 사용되며 instanceof는 참조타입에 사용된다.

typeof 사용예시(MDN Web Docs)

console.log(typeof 42);
// "number"

console.log(typeof 'blubber');
// "string"

console.log(typeof true);
// "boolean"

console.log(typeof undeclaredVariable);
//  "undefined"

// Numbers
console.log(typeof 37) //'number'
console.log(typeof 3.14) //'number'
console.log(typeof(42)) //'number'
console.log(typeof Math.LN2) // 'number'
console.log(typeof Infinity) // 'number'
console.log(typeof NaN) // 'number'
console.log(typeof Number('1')) // 'number      
console.log(typeof Number('shoe')) // 'number   


// Strings
console.log(typeof '') // 'string
console.log(typeof 'bla') // 'string'
console.log(typeof `template literal`) // 'string'
console.log(typeof '1') // 'string'
console.log(typeof (typeof 1)) // 'string'
console.log(typeof String(1)) // 'string'

// Booleans
console.log(typeof true) // 'boolean'
console.log(typeof Boolean(1)) // 'boolean'
console.log(typeof !!(1)) // 'boolean'; 

// Symbols
console.log(typeof Symbol()) // 'symbol'
console.log(typeof Symbol('foo')) // 'symbol'
console.log(typeof Symbol.iterator) // 'symbol'

// Undefined
console.log(typeof undefined) // 'undefined'
console.log(typeof declaredButUndefinedVariable) // 'undefined'
console.log(typeof undeclaredVariable) // 'undefined'

// Objects
console.log(typeof {a: 1}) // 'object'

console.log(typeof [1, 2, 4]) // 'object'

console.log(typeof new Date()) // 'object'
console.log(typeof /regex/) //'object'

// Functions
console.log(typeof function() {}) // 'function'
console.log(typeof class C {}) // 'function'
console.log(typeof Math.sin) // 'function'

 

 

instance of 사용 예시(MDN Web Docs)

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);

console.log(auto instanceof Car);
//  true

console.log(auto instanceof Object);
// true

 

 

 

참조  :

http://milooy.github.io/TIL/JavaScript/call-by-sharing.html

https://velog.io/@aiden/call-by-value-vs-call-by-reference-feat.-call-by-sharing

https://youtu.be/1YFss_4B_o4

https://stackoverflow.com/questions/899574/what-is-the-difference-between-typeof-and-instanceof-and-when-should-one-be-used

https://ddorang-d.tistory.com/87

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof