Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there pointers in javascript?

No, JS doesn't have pointers.

Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like "value" representing the address of an object.

Within a function, one may change the contents of a passed object via that reference, but you cannot modify the reference that the caller had because your reference is only a copy:

var foo = {'bar': 1};

function tryToMungeReference(obj) {
    obj = {'bar': 2};  // won't change caller's object
}

function mungeContents(obj) {
    obj.bar = 2;       // changes _contents_ of caller's object
}

tryToMungeReference(foo);
foo.bar === 1;   // true - foo still references original object

mungeContents(foo);
foo.bar === 2;  // true - object referenced by foo has been modified

You bet there are pointers in JavaScript; objects are pointers.

//this will make object1 point to the memory location that object2 is pointing at
object1 = object2;

//this will make object2 point to the memory location that object1 is pointing at 
function myfunc(object2){}
myfunc(object1);

If a memory location is no longer pointed at, the data there will be lost.

Unlike in C, you can't see the actual address of the pointer nor the actual value of the pointer, you can only dereference it (get the value at the address it points to.)


I just did a bizarre thing that works out, too.

Instead of passing a pointer, pass a function that fills its argument into the target variable.

var myTarget;

class dial{
  constructor(target){
    this.target = target;
    this.target(99);
  }
}
var myDial = new dial((v)=>{myTarget = v;});

This may look a little wicked, but works just fine. In this example I created a generic dial, which can be assigned any target in form of this little function "(v)=>{target = v}". No idea how well it would do in terms of performance, but it acts beautifully.


due to the nature of JS that passes objects by value (if referenced object is changed completely) or by reference (if field of the referenced object is changed) it is not possible to completely replace a referenced object.

However, let's use what is available: replacing single fields of referenced objects. By doing that, the following function allows to achieve what you are asking for:

function replaceReferencedObj(refObj, newObj) {
    let keysR = Object.keys(refObj);
    let keysN = Object.keys(newObj);
    for (let i = 0; i < keysR.length; i++) {
        delete refObj[keysR[i]];
    }
    for (let i = 0; i < keysN.length; i++) {
        refObj[keysN[i]] = newObj[keysN[i]];
    }
}

For the example given by user3015682 you would use this function as following:

replaceReferencedObj(foo, {'bar': 2})