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
Because
the array is passed tothe argument being passedformulas.addby referenceformulas.addis a reference to the private arrayv, any changes you make to its contents will remain visible in the future.The fact that
vis private doesn’t protect its contents when you hand out references tovto external code. It does prevent external code from grabbingvfor itself and swappingvwith another array, but the array itself can be modified (its values changed).