Skip to content Skip to sidebar Skip to footer

JavaScript Array Of Pointers Like In C++

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 Arra

Solution 1:

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


Solution 2:

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

Post a Comment for "JavaScript Array Of Pointers Like In C++"