3
var a = {a: 1, b: 2};
var b = a;
b.a = 3;
In the code above, b. a becomes worth 3, and a. a also becomes worth 3.
var a = {a: 1, b: 2};
function b(objeto) {
objeto.a = 3;
}
b(a);
In the above code, the value of a. a remains 1, because I am not editing the object a, but a copy of it (correct me if I am wrong).
Now here’s the question:
var a = {a: 1, b: 2};
function copy(objeto) {
return objeto;
}
var b = copy(a);
b.a = 3;
In the code above, a. a also worth 3. Why?
I couldn’t reproduce your result from the second snippet of code:
Exception: TypeError: objeto is undefined
.– Pablo Almeida
Code corrected, Pablo.
– André
it seems that he is simply linking object a with b I will put a way I found to make cloning
– Otto
Now
a.a
remains 3.– Pablo Almeida
The closest and simplest to cloning an object would be like this: var copiedObject = jQuery.extend({}, originalObject)
– Otto
If you intend to obtain a complete copy at all times, take a look at this question: http://answall.com/a/881/26404
– Pablo Almeida
The second code shall include the
a
changed to 3. The object is passed by reference. You are changing the object itself and not a copy.– Maniero
My goal is not to make a copy. I want to understand why this happens. What is the difference between the second code and the third code? Why one modifies the object and another does not?
– André