-2

I am using a Module Pattern in a javascript code, initially i have to make a private property equal to another, but it looks like it's just a symlink, like in the example. I need two independant private properties but sometimes sync them.

Thanks for help.

Maxime.

    var module = (function () {

    var data1 = {
        pro1 : "aaa",
        pro2 : "bbb"
    };

    var data2 = {};

    function init() {
        data2 = data1;
    }

    function logg() {
        console.log(data1);
        console.log(data2);
    }

    function test() {
        data2.pro1 = 'haha';
    }

    return {
        init : init,
        logg : logg,
        test : test
    }

}());

module.init();

module.logg();

// data1 = { pro1 : "aaa", pro2 : "bbb" }
// data2 = { pro1 : "aaa", pro2 : "bbb" }

module.test();

module.logg();

// data1 = { pro1 : "haha", pro2 : "bbb" }
// data2 = { pro1 : "haha", pro2 : "bbb" }
Rdb Max
  • 23
  • 5

1 Answers1

0

If your simple object example is similar to the structure you're going to be using, aka no prototypical inheritances from your objects, you could loop through your object and assign values from your old to new. Otherwise your simple assignment will just be pass by reference.

ie:

for(var i in data1){
    data2[i] = data1[i];
}
ecMode
  • 530
  • 3
  • 16