I’m wanting to directly update the object referred by a function argument from within the scope of that function. An example:
var thisObj = { "val" : "original value" };
function modFunc(objRef) {
objRef = { "val" : "modified" };
console.log(objRef); // { "val" : "modified" }
}
console.log(thisObj); // { "val" : "original value" };
I understand why this happens, and I realize that I could have used
objRef.val = "modified";
within modFunc to perform the modification. For reasons specific to my project though, I would like to be able to accomplish something like:
function modFunc(objRef) {
objRef.self = { "val" : "modified" }; // Of course this will not work,
// but is there an Object property or method that allows one to access
// the actual memory pointer being referenced by the variable?
}
where I can specify that I want to directly modify thisObj to reference the new object that I instantiate within modFunc. Is this possible? I know there are tools like Object.assign() that I could use to do this but it’s not supported universally, or library tools like bind() that I could use if I imported the library, but it just seems like there might be some native syntax that would allow me to do this and I just haven’t been able to find it?..
I’ve spent some time looking, otherwise I try not to ask questions like this. I also know there are other similar posts to this one, but nothing exactly like what I’m asking and I don’t have the ‘reputation’ here to be able to respond directly to posts etc. so I didn’t see an easy way to focus the discussion. Anyway, thanks for any help!
What you’re asking for is, essentially, a call-by-reference mechanism, or the ability to explicitly create a reference to a variable. In JavaScript, that’s not possible. You can (as you note) pass around references to objects and use those to modify object property values (and to add and remove properties, even), but that’s not quite the same thing.