2

I have the following struct (or class?) in JavaScript:

function ImageStruct() {
    this.id = -1;
    this.isCover = true;
    this.isPaired = false;
    this.row = -1;
    this.column = -1;
} 

I add this class to a bidimensional array.

var imgStruct = new ImageStruct();
imgStruct.id = id;
imgStruct.row = row;
imgStruct.column = column;

$.myNameSpace.matrixPos[row][column] = imgStruct;

When I do something like this:

var imgStrc = $.myNameSpace.matrixPos[row][column];

If I modify imgStrc, object in $.myNameSpace.matrixPos[row][column] doesn't reflect that changes.

Is there any way to 'fix' this?

VansFannel
  • 45,055
  • 107
  • 359
  • 626
  • Related: http://stackoverflow.com/questions/518000/is-javascript-is-a-pass-by-reference-or-pass-by-value-language – Orbling Jun 04 '11 at 19:20
  • `$.myNameSpace.matrixPos[row][column] = imgStrc` again after modifying it. – Orbling Jun 04 '11 at 19:24
  • @Orbling: I know this is a possible solution, but I want to know if there is another one. Thanks for your comments. – VansFannel Jun 04 '11 at 19:26
  • 1
    I would also recommend againts treating javaScript like C (by thinking in terms of structs and pointers). it's best to treat JS as a prototyping OO / functional hybrid. – Raynos Jun 04 '11 at 19:36
  • @Raynos: I didn't explain it very well. I'm trying to say if imgStrc is a reference of an existing object or if it's a new instance. – VansFannel Jun 05 '11 at 06:44

4 Answers4

2

It definitely should be "by reference". I set up a JsFiddle to confirm.

http://jsfiddle.net/bJaL4/

Structs aren't really possible in JavaScript. There are explicit value and reference types. All objects are treated as reference types.

Neil
  • 1,206
  • 9
  • 7
2

If you modify imgStrc it by changing its properties (e.g. by doing imgStrc.id = 42), that change will affect the object in $.myNameSpace.matrixPos[row][column] (as it is in fact the same object).

Only if you modify imgStrc by reassigning it, it won't. There is no way to 'fix' this, other than setting $.myNameSpace.matrixPos[row][column] = imgStrc or wrapping the whole thing into a wrapper object (or one-element array).

sepp2k
  • 363,768
  • 54
  • 674
  • 675
1

You can either modify the object directly:

$.myNameSpace.matrixPos[row][column].someMethod();

which is admittedly not very convenient, or feed the value back into the array after modifying it:

var tmp = $.myNameSpace.matrixPos[row][column];

tmp.someMethod(); // Do something...

$.myNameSpace.matrixPos[row][column] = tmp;
Félix Saparelli
  • 8,424
  • 6
  • 52
  • 67
1

JavaScript doesn't have pointers. You last var statement just overwrites the imgStrc value with the value of the namespace property. Whatever that value is is what you modified. If it's an object, all references to that obj will see the change.

AutoSponge
  • 1,444
  • 10
  • 7