I’m faced with a situation in JavaScript when I need to update an object via its pointer similar to С++ array of pointers to objects
Example code for my issue:
var foo = new Array();
var bar = function(){
this.test = 1;
foo.push(this); // push an object (or a copy of object?) but not pointer
};
var barInst = new bar(); // create new instance
// foo[0].test equals 1
barInst.test = 2;
// now barInst.test equals 2 but
// foo[0].test still equals 1 but 2 is needed
So, how can I solve this? Should I use a callback or something like this or there is an easy way to help me to avoid copying the object instead pushing the raw pointer into an array?
JS is pass-by-value, so your original assignment was
this.test = the value of 1, in my example, it’sthis.test = the object pointed to by ptr, so when I changeptrthis.testchanges as well.Although if you thought that
foo.push(this);was similar, it isn’t. Since this is an object, the array will indeed contain “raw pointers” to objects, just like you want. You can prove this simply:Which shows that it is indeed a pointer to the object that was pushed onto the array