user5381186 user5381186 - 1 year ago 99
Javascript Question

Javascript mixin for objects whose properties are objects ambiguity

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 = {
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download