Skip to content Skip to sidebar Skip to footer

Variable Re-assignment Of Object Reference Leaves Other Object Unaltered (no “transitive” Assignment)

I have an object that I want to replace. var obj1 = { x: 'a' }; var ref = obj1; var obj2 = { y: 'b' }; obj1 = obj2; This results in ref being equivalent to { x: 'a' }, but I want

Solution 1:

Not possible. JS passes objects by a copy of the reference, so in the step var ref = obj1 you're not actually assigning a reference pointer like you would in a language like C. Instead you're creating a copy of a reference that points to an object that looks like {x: 'a'}.

See this answer for other options you have: https://stackoverflow.com/a/17382443/6415214.

Solution 2:

You can try to change all the fields of obj1 with the fields of obj2

var obj1 = { x: 'a' };
varref = obj1;
var obj2 = { y: 'b' };
obj1.x = obj2.y;
console.log(ref) // Print {x, 'b'}

If you want to add {y,'b'} you can follow the approach

obj1.y=obj2.y
console.log(obj1); prints {x: "b", y: "b"}
console.log(ref); prints {x: "b", y: "b"}

If you instead want to delete obj1.x you can do something like this

delete obj1.x;
console.log(ref) prints {y:'b'}

Post a Comment for "Variable Re-assignment Of Object Reference Leaves Other Object Unaltered (no “transitive” Assignment)"