1

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?

4
  • Don't you mean barInst.test = 2? bar is a constructor, not an object. That is foo[0] does not equal bar... Commented May 17, 2011 at 8:57
  • Oh, sorry. Yes, I meant barInst.test instead of bar.test Commented May 17, 2011 at 9:03
  • In which case, your code should work. Does it? see: jsfiddle.net/p6LQh Commented May 17, 2011 at 9:13
  • Oh.. Yeah it works.. And also I take a look into original sources and found an error and this is not a problem anymore. Both of code snippets (original and davin's code) are working. Thanks a lot for assistance! Commented May 17, 2011 at 9:25

2 Answers 2

4

JS is pass-by-value, so your original assignment was this.test = the value of 1, in my example, it's this.test = the object pointed to by ptr, so when I change ptr this.test changes as well.

var foo = [],
    ptr = {val: 1},
    bar = function(){ 
       this.test = ptr;
       foo.push(this); // push an object (or a copy of object?) but not pointer
    },
    barInst = new bar(); // create new instance
    // foo[0].test.val equals 1
    ptr.val = 2;
    // foo[0].test.val equals 2

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:

foo[0].test = 3;
// barInst.test === 3

Which shows that it is indeed a pointer to the object that was pushed onto the array

Sign up to request clarification or add additional context in comments.

Comments

0

"create object method pointer"

Object.defineProperty(Object.prototype,'pointer',{
    value:function(arr, val){
       return eval(
                  "this['"+arr.join("']['")+"']"+
                   ((val!==undefined)?("="+JSON.stringify(val)):"")
                  );
     }
});

ex of use

var o={a:1,b:{b1:2,b2:3},c:[1,2,3]}, arr=['b','b2']
o.pointer(arr)  // value 3
o.pointer(['c',0], "new_value" )

1 Comment

could rise problems not escaped '

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.