Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 it to get changed as well to point to obj2 to get ref being equivalent to { y: "b" }.

like image 857
Chris Avatar asked Jan 23 '17 19:01

Chris


People also ask

Does object assign change reference?

Object. assign is copying the activities object, but still keeps references to it, so if I find a specific activity and change some property on it, it changes the original too!

How do you point a variable in JavaScript?

TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference.


2 Answers

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.

like image 58
Charles Avatar answered Oct 03 '22 16:10

Charles


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

var obj1 = { x: 'a' };
var ref = 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'}
like image 44
Md Johirul Islam Avatar answered Oct 03 '22 17:10

Md Johirul Islam