When copying an object are they subject to the same changes?

0

I am using a tool that serves to create user surveys. The tool generates a page (the survey) with a JS object in which there is information about the user's interaction with the questions and some utilities (methods) and that she herself uses to generate questions, allow page breaks, validate, obtain values of the answers, etc ... Therefore, if I want to check the value of something or execute some method when I'm testing it, I just have to go to the console and do it.

The problem is that this is only possible when you launch the survey. When I test the survey through this tool, what it does is insert this final result in an iframe. This is because, as a test mode, it gives me certain tools in a menu that the end user will not see. Then accessing the object mentioned above becomes more problematic. Well nothing happens, with window.frames [0] I can access the window object of the iframe. So I decide to create an object called "Clone" in the scope of the parent window with the window object of the iframe.

So far everything is perfect, this is allowing me to consult and execute methods with ease as well as consult the variables hosted in the window object of the iframe, etc. But I believed that being a copy if I modified some value, some property of the object, it would only be altered in the clone. For example: Clone.ObjectOfTheTool.Question4.UserElection = 5; But to my surprise I see that modifying the "Clone" object also modifies the iframe object.

Is this normal? Why does it happen, because they are linked?

This really is not an inconvenience for me but an advantage but curiosity springs up. Although not only that, but at the same time I worry about assimilating that they are totally "linked" and that this is not the case, and that in the future, when I try to modify the original using the Clone, errors that totally go unnoticed occur due to this .

Are they fully linked, do any changes I make to one apply exactly to the other?

Thank you very much in advance! (:

    
asked by Adrià Fàbrega 23.08.2018 в 13:58
source

1 answer

1

When you tried to copy the objects

obj1 = obj2

What you copied was the reference, not its values. Therefore the two variables point to the same instance of the object.

var obj1 = {prop : "Valor Original Objeto 1"}
var obj2 = {prop : "Valor Original Objeto 2"}

console.log(obj1.prop)
console.log(obj2.prop)

obj1 = obj2

console.log(obj1.prop)
console.log(obj2.prop)

obj2.prop = "Valor Despues de Copiar"

console.log(obj1.prop)
console.log(obj2.prop)

To "clone / copy" objects, you should copy value by value

var obj1 = {
    this.prop1  = obj2.prop1,
    this.prop12 = obj2.prop2
    ...
}

For some simple cases, you could also treat the object as a json

var obj1 = JSON.parse(JSON.stringify(obj2));
    
answered by 23.08.2018 в 16:06