0

Good morning, I've encountered a strange behavior of assignments in javascript. The behavior is replicable outside the specific project, here's how to trigger it:

function A_n(){
    var u=100;
    this.get=function(){
        return u;   
    }
}

function B_n(){
    var e={'g':'','f':new A_n()};
    this.get=function(){
        var result=e;
        var tmp=e.f.get();
        result.f=tmp;
        return result;
    }
}

If I called the "get" method of the instance of the class "B_n" the code would return the correct value (the result of the "get" method of the class "A_n"), but without any reason it reassigns this result to the private variable "e " of the instance of "B_n". Proof of the fact that if we called "a.get()" a second time, it would give an error since "e" would no longer be an object of type "A_n".

var a=new B_n();
console.log(a.get());
{g: '', f: 100}
console.log(a.get());
Uncaught TypeError: e.f.get is not a function
    at B_n.get (<anonymous>:12:15)
    at <anonymous>:1:15

The problem in the project has been worked around, I would be grateful if someone could explain to me what happens. Thank you

  • I'm not a Javascript developer, but it assigns `tmp` to `e.f`, not `e`... because `result` and `e` refer to the same object. (In other words, this is what I'd expect if Javascript uses roughly similar behavior to reference types in Java and C#... modulo static/dynamic typing.) – Jon Skeet Jul 26 '23 at 10:11
  • 2
    `result=e` does not create a *copy* of the `e` object. There's still only one object, which you're modifying. Nothing "reassigns `e`", but the object that both `e` and `result` refer to gets modified. – deceze Jul 26 '23 at 10:12
  • To solve the issue, make a copy of `e` before modifying it. `var result = { ...e };` Note that this is a shallow copy and only allows for mutations on `result`, not on anything nested inside. (So `result.f = ...` is fine, but `result.f.g = ...` is not.) Going any deeper would mean you need to make more copies. – 3limin4t0r Jul 26 '23 at 10:49

0 Answers0