0

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>
user3840170
  • 26,597
  • 4
  • 30
  • 62
Micha Schopman
  • 221
  • 2
  • 14
  • 1
    The `fooProperty = "…";` line cannot possibly affect the proxy. `fooProperty` is a local variable, and you were passing a string for the parameter (by value, as always). Not sure what you expected there? It's not an "object property" any more. – Bergi Sep 16 '20 at 15:23
  • I think I need some vacation. You are right. I am passing a primitive value.... – Micha Schopman Sep 16 '20 at 15:29
  • I will rephrase the question accordingly because now looking back I was asking the wrong question and also provided an incorrect coverage of the issue I have. I will create a new question for this to avoid confusion. Thanks. – Micha Schopman Sep 16 '20 at 15:54
  • You can also [edit] this question and I'll reopen it. – Bergi Sep 16 '20 at 15:57
  • I found the issue and solution Bergi, https://stackoverflow.com/questions/41299642/how-to-use-javascript-proxy-for-nested-objects Thanks for the support though – Micha Schopman Sep 16 '20 at 16:08

0 Answers0