ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 원시 타입과 참조 타입
    자바스크립트 2023. 3. 23. 16:44

    I. 값 복사 결과 비교

    1. 원시 타입 - 값에 의한 복사 copy by value

    let number1 = 1;
    let string1 = 'ABC';
    let bool1 = true;
    
    let number2 = number1;
    let string2 = string1;
    let bool2 = bool1;
    
    number2 = 2;
    string2 = '가나다';
    bool2 = false;
    
    console.log('~1:', number1, string1, bool1); //~1: 1 ABC true
    console.log('~2:', number2, string2, bool2); //~2: 2 가나다 false

    이 코드를 실행하면 다음과 같은 일이 일어난다.

    2. 참조 타입- 참조에 의한 복사 cpoy by reference

    배열과 객체가 있다.

    우선 객체먼저 살펴보면 다음과 같다.

    const obj1 = {
      num: 1, str: 'ABC', bool: true
    };
    const obj2 = obj1;
    // obj2 = {}; // ⚠️ 오류
    
    console.log('obj1:', obj1);
    console.log('obj2:', obj2);
    
    // ⭐️ const임에도 내부 값은 변경 가능함 주목
    // 내부 변경 방지는 이후 배울 Object.freeze 함수로
    obj2.num = 2;
    obj2.str = '가나다';
    obj2.bool = false;
    
    console.log('obj1:', obj1);
    console.log('obj2:', obj2);
    //obj1과 obj2의 프로퍼티의 값이 둘 다 변경됐다

    여기서 주의깊게 봐야할 부분은 왜 obj2의 프로퍼티의 값을 바꿨는데 obj1의 프로퍼티의 값이 같이 바뀌었나~이다. 

     

    배열도 한번 살펴보자.

    const array1 = [1, 'ABC', true];
    const array2 = array1;
    // array2 = []; // ⚠️ 오류
    
    console.log('array1:', array1);
    console.log('array2:', array2);
    
    // ⭐️ const임에도 내부 값은 변경 가능함 주목
    array2[0] = 3;
    array2[1] = 'def';
    array2[2] = false;
    
    console.log('array1:', array1);
    console.log('array2:', array2);
    //둘다 프로퍼티 값이 변경됨

    역시 array2의 요소만 변경했는데 array1의 요소도 같이 바뀐 것을 볼 수 있다.

    왜 그런지는 다음 그림을 보면 알 수 있다. 

    간단히 말하자면 값을 복사해 온 것이 아니라 그 값을 가리키는 주소를 복사한 것이다. 

     

    이번엔 메모리 영역에서 확인해보자.

    const obj1 = {
      num: 1,
      str: 'ABC',
      bool: true
    };
    
    const obj2 = obj1;
    
    obj2.num = 2;
    
    console.log(obj1, obj2);

    obj1과 obj2는 어떤 값들을 가지고 있는 주소값을 공유한다 (값 그 자체가 아니라).

    obj2.num = 2로 그 주소에 있는 값을 변경하면 obj1도 같은 주소를 가리키고 있기 때문에 obj1역시 프로퍼티 값의 변경이 일어나는 것이다.

     

    배열도 마찬가지다. 

    const array1 = [1, 'ABC', true];
    const array2 = array1;
    
    array2[1] = '가나다';
    
    console.log(array1, array2);

Designed by Tistory.