简体   繁体   中英

Object array: reference to existing objects or new instances

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?

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.

If you modify imgStrc it by changing its properties (eg 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).

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM