Reputation: 556
here is the fiddle: http://jsfiddle.net/Xh4GU/1 or the code:
function Vector()
{
var v = new Array(123, 456, 789);
this.getV = function()
{
return v;
}
}
function Formulas()
{
this.add = function(x, axis, units)
{
x[axis] += units;
}
}
var vector = new Vector();
var formulas = new Formulas();
var v = vector.getV();
var vAdded = formulas.add(v, 0, 77)
document.write(v);
spits out: 200,456,789
Why is the first index of v being changed? Thanks
Upvotes: 2
Views: 123
Reputation: 437444
Because the array is passed to the argument being passed formulas.add
by referenceformulas.add
is a reference to the private array v
, any changes you make to its contents will remain visible in the future.
The fact that v
is private doesn't protect its contents when you hand out references to v
to external code. It does prevent external code from grabbing v
for itself and swapping v
with another array, but the array itself can be modified (its values changed).
Upvotes: 2
Reputation: 16795
This is happening because you are referencing not copying v
, please see my demo for a more clear-cut example: http://jsfiddle.net/SO_AMK/hjtLd/ If you click the button after it generates the numbers you will see that the result is a different array.
However, if you move the array to inside vector.getV()
you will see that the result will consistently be 123,456,789. This is because you would be resetting the value of v
every time the function is run.
You could also create a "real" copy, like this: http://jsfiddle.net/SO_AMK/J8h4d/
Upvotes: 0
Reputation: 96810
var vAdded = formulas.add(v, 0, 77)
You're saying to add the first index of the array (v[0]
) by 77. Why? The private variable v
is returned by this.getV
. When you did
var v = vector.getV();
it returned a reference to the array. This effectively allows you to interact with the array outside of the function.
Upvotes: 0
Reputation: 23208
Because you changing it v is an array and you are changing it in Formulas. jsfiddle
var vector = new Vector();
document.write(v.toString()); // 123,456,789
var formulas = new Formulas();
var v = vector.getV();
var vAdded = formulas.add(v, 0, 77).// v getting changed inside formulas.add.
document.write(v); //200,456,789
Upvotes: 0