0

From a function, I would like to return a modified version of an object passed as an argument, without affecting the original object (i.e. side effect free). So essentially I want to pass by value. I have tried to do this by modifying and returning a (deep) copied version of the object. However I have now found that modifications I make to to the cloned object are still affecting the original.

The code snippet below demonstrates this, as calling modifyMyData on newObject will affect the data of oldObject

var clone = function(oldObject) {
    return jQuery.extend(true, {}, oldObject);
}

var objf = function() {
    var data = {list:[1],dic:{a:'3'}};
    this.modifyMyData = function() {
        data.list.push(3);
        data.dic['e'] = 10;
    }
    this.getData = function() {
        return data;
    }
}

var old = new objf;
var newo = clone(old);
newo.modifyMyData();

How can I get around this?

zenna
  • 9,006
  • 12
  • 73
  • 101

1 Answers1

1

Try this I think it work like you want it to. You need to attach the variable data to the object. The way you were doing it turned it into a variable with a closure so it didn't get copied.

var clone = function(oldObject) {
    return jQuery.extend(true, {}, oldObject);
}

var objf = function() {
    this.data = {list:[1],dic:{a:'3'}};

    this.modifyMyData = function() {

        this.data.list.push(3);
        this.data.dic['e'] = 10;
    }
    this.getData = function() {
        return this.data;
    }
}

var old = new objf();
var newo = clone(old);
newo.modifyMyData();
qw3n
  • 6,236
  • 6
  • 33
  • 62