Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - JS object copy by value vs copy by reference

I was playing with chrome console and noticed something which I couldn't understand. I know in JS variables are copied by value and objects are copied by reference. Below code works fine as expected which outputs 2 and proves JS objects work as reference:

var objA = {a: 1};
var objB = objA;
objA.a = 2; 
objB.a; // 2

However this code doesn't work as it should. I expected objB.a to output 2 but it gives 1 instead. Why?

var objA = {a: 1};
var objB = objA;
objA = {a: 2};  //Assigned whole object here instead property.
objB.a; //1 - Shouldn't this be 2 ??
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'd rather think of variables with objects as pointers to objects (like C pointers) rather than references.

In your third line, you just replaced objA, making it "point to" another object. It does not change whatever objB is "pointing".

By line 3, objA now points to {a:2} while objB still points to whatever objA was pointing at the time you assigned it to objB, at line 2, which is {a:1}.

line 1: objA -> {a:1}
line 2: objA -> {a:1} <- objB
line 3: objA -> {a:2}, objB -> {a:1}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...