0

Here is a user-defined mixin for shallow cloning of objects:

    function mixin(receiver, supplier) {
      Object.keys(supplier).forEach(function(key) {
         receiver[key] = supplier[key];
      });

      return receiver;
    }
    var supplier = {
        a:{b:10}
    };
    var receiver = mixin({},supplier);

and according to my understanding assigning one object to other makes them equal since they have reference to same object literal and when one object changes its property it reflects on the other object too but the below tests puzzled me:

    receiver.a === supplier.a //true
    receiver.a = {b:20} //but
    supplier.a //still {b:10} I expected {b:20}

What am I doing wrong here?? P.S I know about ES6 Object.assign() but this mixin is created just for my understanding.

socket_var
  • 1,063
  • 2
  • 11
  • 18

1 Answers1

2

The assignment is different from every other operation. It breaks the references because of how it works.

Basically, you have the object in memory, and every variable contains a pointer to the memory location. Thus when you edit that object, you change every reference of it.

But if you assign a variable a new value, it puts a new object in a new position in the memory, and changes the reference pointer to the pointer of the new location.

enter image description here

Bálint
  • 4,009
  • 2
  • 16
  • 27
  • But I only changed property b of the already existing object literal {b:10} pointed by both objects a and b.For me it looks the same as normal object pass by references and I still think a and b still point to the same object literal. :( – socket_var Oct 25 '16 at 18:51
  • @user5381186 No, you created a new object with `{b: 20}`. If you want to change `b`, then you need to do `receiver.a.b = 20` – Bálint Oct 25 '16 at 18:56
  • WHoops yeah I got it – socket_var Oct 25 '16 at 19:01