0

I have two files in Node.js where one requires the other one.

variable_test.js:

TEST        = require('./variable_test_external.js');

TEST.get(function(myVariable) {
    var changeMeVariable;
    console.log(myVariable);
    changeMeVariable = myVariable.epicVariable;
    changeMeVariable.evenEpicerVariable = "test3";
    TEST.get(function(myVariable2) {
        console.log(myVariable2);
    });
});

variable_test_external.js:

var testVariable = new Array({epicVariable: {evenEpicerVariable: "test1"}}, {epicVariable: {evenEpicerVariable: "test2"}});

exports.get = function(callback) {
    callback(testVariable[1]); // I know that the return is unnecessary in this example but in my real application I have return there for compactness.
}

This is the output when run in Node.js with node variable_test.js:

{ epicVariable: { evenEpicerVariable: 'test2' } }
{ epicVariable: { evenEpicerVariable: 'test3' } }

The console.log(myVariable) changes in the two TEST.get's. Why does this happen?

Emil Hemdal
  • 589
  • 2
  • 8
  • 27
  • You're changing the property value with `changeMeVariable.evenEpicerVariable = "test3";`. Why do you expect it *not* to change? You never make a copy of any of the objects, so they are still all the same objects. – apsillers Dec 03 '13 at 16:57
  • See also [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/a/3638034/710446) – apsillers Dec 03 '13 at 17:00
  • Ah I see. Thanks for the info! Is there an easy way of copying the object so that I don't change the original when I edit the copy? – Emil Hemdal Dec 03 '13 at 21:03

2 Answers2

0

This is a reference copy, not a value copy. You got the object from the array, NOT a copy of them.

changeMeVariable = myVariable.epicVariable;

This would have to fix yout problem

// PSEUDO CODE, i don't know the correct syntax 
changeMeVariable = {
    epicVariable = myVariable.epicVariable
};
n0m
  • 1
0

The answer in my case is the following based on the links at the bottom:

changeMeVariable = JSON.parse(JSON.stringify(myVariable.epicVariable));

But, it's much better to manually copy it like the bottom most link like this:

changeMeVariable = {
    evenEpicerVariable: myVariable.epicVariable.evenEpicerVariable
}

n0m's answer is similar but if the epicVariable.evenEpicerVariable contained an object that object's reference would still be linked! (I tested it)

References:

What is the most efficient way to deep clone an object in JavaScript?

http://jsperf.com/cloning-an-object/3

Community
  • 1
  • 1
Emil Hemdal
  • 589
  • 2
  • 8
  • 27