[英]Object array: reference to existing objects or new instances
I have the following struct (or class?) in JavaScript:我在 JavaScript 中有以下结构(或 class?):
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.我将此 class 添加到二维数组中。
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.如果我修改
imgStrc
, $.myNameSpace.matrixPos[row][column]
中的 object 不会反映该更改。
Is there any way to 'fix' this?有没有什么办法解决这一问题?
It definitely should be "by reference".它绝对应该是“通过引用”。 I set up a JsFiddle to confirm.
我设置了一个 JsFiddle 来确认。
http://jsfiddle.net/bJaL4/ http://jsfiddle.net/bJaL4/
Structs aren't really possible in JavaScript. 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).如果您通过更改
imgStrc
的属性来修改它(例如通过执行imgStrc.id = 42
),该更改将影响$.myNameSpace.matrixPos[row][column]
中的 object (因为它实际上是同一个对象)。
Only if you modify imgStrc
by reassigning it, it won't.仅当您通过重新分配
imgStrc
来修改它时,它才不会。 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).除了设置
$.myNameSpace.matrixPos[row][column] = imgStrc
或将整个东西包装到包装器 object (或单元素数组)中之外,没有办法“修复”这个问题。
You can either modify the object directly:您可以直接修改 object:
$.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. JavaScript 没有指针。 You last var statement just overwrites the imgStrc value with the value of the namespace property.
您最后的 var 语句只是用命名空间属性的值覆盖了 imgStrc 值。 Whatever that value is is what you modified.
无论该值是什么,都是您修改的值。 If it's an object, all references to that obj will see the change.
如果它是 object,则对该 obj 的所有引用都会看到更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.