OO Javascript copy of object
This question already has an answer here:
In JS, all assignments are done by value.
However, in the case of objects, that value is a reference.
That is, if you use yellow = blue
, both yellow
and blue
will contain the same object in memory. So you can't alter one without modifying the other one.
In the first case:
var blue = {a:1};
var yellow = blue; // yellow references blue...
yellow = 3; // but not anymore. Now it's just a number.
In the second:
var blue = {a:1};
blue.b = 2;
var yellow = blue // yellow references blue
yellow.c = 3; // and still does, so yellow.c and blue.c are the same`
When you assign a value to a variable, whatever value that variable had before is gone. That's what happens in your first sample.
When you assign a variable to a value that is an object, and you then modify that object (setting a property of it to some value), you still have that variable pointing that object. That's what happens in your second sample.
The other thing that happens in your second sample is that blue
& yellow
point to the same object, so modifying via blue
is identical to modifying via yellow
, and in both cases the effect "applies" to both variables (it's always the same object)
上一篇: 变量引用更改
下一篇: OO对象的Javascript副本