I am trying to find an explanation for behavior with - what I expected to be - a reference type but actually loses reference once supplied as an argument. Any changed made on the property are not reflected on the original object.
When I provide the full object, and make changes it gets noticed by the proxy. When I provide the property and make changes it doesn't get noticed. I've done my fair share of javascript code but this one is pretty confusing.
Normally I have to really do a JSON.parse((JSON.stringify(foo)) to make a deep copy and really get rid of any reference but this time I really only wanted to provide the property to the object as an argument and avoid sharing the entire object as an argument.
I have build a test case that shows exactly what is happening.
<html>
<head><title></title></head>
<body>
<script>
var state = {};
state.Foo = 'default value for Foo';
function TwoWayBinding(state) {
this.state = this.WrapWithProxy(state);
}
TwoWayBinding.prototype.WrapWithProxy = function (state) {
const handler = {
get: function(target, prop) {
return target[prop];
},
set: function(target, prop, value) {
console.log(prop,value);
target[prop] = value;
return true;
}
};
return new Proxy(state, handler);
};
var twoWayBinding = new TwoWayBinding(state);
state = twoWayBinding.state;
function Test(fooProperty,fullState){
fooProperty = "changed value A, check console"; // fails
fullState.Foo = "changed value B, check console"; // works
// additional tests
this.state = fullState;
this.test = this.state.Foo; // breaks reference
this.state.Foo = 'changed value C, check console'; // works
this.test.Foo = 'changed value D, check console'; // fails
}
new Test(state.Foo,state);
</script>
</body>