开发者

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][colu开发者_开发技巧mn] = 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?


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).


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜