[JS] 얕은 복사, 깊은 복사

daun·2022년 8월 10일
0

[오답노트]

목록 보기
25/26

모던 자바스크립트 딥 다이브를 보면서 이해가 안되는 예제(p.153)

꼭 다시 보자!

결론

객체를 할당한 변수는 참조값을 가지고 있다.
따라서 상수 a,b는 참조값을 가지고 있다.
따라서 내용은 같아도, 다른 메모리에 저장된 별개의 객체이다.
즉, a와 b의 참조값은 전혀 다른 값이다. 따라서 false가 된다.

하지만, 프로퍼티 값을 참조하는a.name와 b.name는 값으로 표현될 수 있는 표현식이다.
두 표현식 모두 원시 값 'Lee'로 평가된다.

JS koans

   function passedByReference(refObj) {
     refObj.henchwoman = "Adam West";
   }
   passedByReference(obj);
   expect(obj.henchwoman).to.equal("Adam West");

   const assignedObj = obj; // 참조를 전달
   assignedObj["relations"] = [1, 2, 3];
   // 참조 주소를 복사하였기 때문에, 주소에 따른 원 객체를 변경할 수 있다.
   expect(obj["relations"]).to.deep.equal([1, 2, 3]);
   // Object.assign(target, source);
   const copiedObj = Object.assign({}, obj);
   // 주소를 복사한 것이 아니라, 새로운 객체를 생성한 것이라서
   // 원 객체와 영향받지 않는다.
   copiedObj.mastermind = "James Wood";
   expect(obj.mastermind).to.equal("Joker");

   obj.henchwoman = "Harley";
   expect(copiedObj.henchwoman).to.equal("Adam West");

   delete obj.twins["Jared Leto"];
   // 엥? 왜?
   expect("Jared Leto" in copiedObj.twins).to.equal(false);
profile
Hello world!

0개의 댓글