I understand that javascript is always "Pass-by-value". Even when when assigning an object, it passes a value which is a reference to the object.
1: var obj1 = {name: "bob"};
2: var obj2 = obj1;
3: obj2.name = "joe";
4: console.log(obj1.name); // output: "joe"
5: obj2 = {name: "ron"};
6: console.log(obj1.name); // output: "joe"
On line 4, both obj1
and obj2
contain a reference to the same object, and that we are able to manipulate that object through both variables. But line 5 sets obj2
to refer to a new object. now obj1
and obj2
have references to 2 different objects. This all makes sense so far.
My question is this: is there any way to access the object itself and not just references to it? So that instead of simply manipulating the object we can change it to a whole new object and any variables that referenced it would now reference the new object? something like this:
var obj1 = {name: "bob"};
var obj2 = obj1;
var actualObject = GetActualObjectReferencedBy(obj2);
actualObject = new Date();
console.log(obj1) // output: the current date;
console.log(obj2) // output: the current date;
So that actualObject
is just that. the actual object that everything is referring to, not just a reference. And making ANY changes to it doesn't break the references.
Here is an example of why I want to do this:
function Person(n){
this.name = n;
}
function attachProxies(){
for(var i = 0; i < arguments.length; i++){
var actualObject = GetActualObject(arguments[i]);
actualObject = new Proxy(actualObject, {
get: function(obj, prop){ return "I'm " + obj[prop]; };
});
}
}
var guy1 = new Person("bob");
var guy2 = new Person("joe");
var guy3 = new Person("rom");
attachProxies(guy1, guy2, guy3);
console.log(guy2.name); // output: "I'm joe"
The closest thing I can figure is this:
function attachProxies(obj){
return new Proxy(obj, {
get: function(obj, prop){return "I'm "+obj[prop];};
});
}
var guy1 = new Person("bob");
var guy2 = new Person("joe");
var guy3 = new Person("rom");
guy1 = attachProxies(guy1);
guy2 = attachProxies(guy2);
guy3 = attachProxies(guy3);
But that's much more limited and repetitive.
I've tried looking around but I can't seem to find any way of doing this. If it's not possible, please help me understand the reasoning.
Edit:
I don't believe this counts as a duplicate because I acknowledge in the setup to my question that javascript passes by value. The supposed duplicate only states that but does not answer my question of whether there is any way access the object.