I understand that JavaScript objects, including arrays, are automatically passed by reference, so I have something like this:
class Thing {
constructor( ) {
this.letters = [ "A", "B" ];
this.numbers = [ 1, 2, 3 ];
this.change( this.letters, this.numbers );
}
change( _letters, _numbers ) {
let l = _letters;
let n = _numbers;
l = [ ];
n = 6;
}
}
var t = new Thing( );
console.log( t );
The log request shows that there has been no change to the properties of Thing. And yet, under different conditions that I can not recognise, I have accidentally modified passed parameters inside a function, and have had to use something like n = Array.from( _numbers )
to avoid modifying the source property. Would someone be able to explain what is happening, and why?
I would like to pass object properties by reference such that I can modify more than one related property in a single function call, and thereby reserve the return value for debugging purposes.
Thank you.
_letters[1] = 'C'
orl[1] = 'C'
change()
,l
andn
are references to your class's properties. However, on the next two lines, you reassign those variables to now be references to an empty array and 6.l
andn
no longer reference your class's properties, they now reference values declared in the scope ofchange()
.l
andn
are not references. All they do is hold the same object reference as thethis.letters
andthis.numbers
properties respectively.