0

I got an object defined global way:

window.myobj = {};

Then new elements are being added and finally it is being saved via ajax to database by SaveData(obj) function. The problem is, that I am making it alot of times in short period, and it seems that what is being passed to function is only a pointer to one single object, so when another event occures, it changes inside a save function even when it was changed outside. In PHP, you have to use &$obj for it... so how do I do it properly, so the obj passed to the function would not be only a pointer?

Edit: The problem appeared in here:

Lets say that event = {time:123,type:blah}

function SaveData(event){
  obj = jQuery.extend({}, event); // doesn't seem to replicate event
  $.post('save',obj,function(res){
    if(res) console.log(obj);
  });
  if(obj.type == 'blah'){
     newobj = jQuery.extend({}, obj);
     newobj.type = 'newtype';
     newobj.time = 234;
     SaveData(newobj);
  }else if(obj.type == 'newtype'){
     newobj = jQuery.extend({}, obj);
     newobj.type = 'lasttype';
     newobj.time = 345;
     SaveData(newobj);  
  }
}

This returns 3 objects that are the same:

{time:345,type:lasttype}
Flash Thunder
  • 11,114
  • 7
  • 42
  • 84

2 Answers2

0

Assuming your Object myobj does not contain any functions, but only values and further objects, one very easy way to clone the Object (and thus get rid of the problem with pointers) would be:

var clonedObj = JSON.parse(JSON.stringify(window.myobj));

Now you can pass the clonedObj to your SaveData Function.

burnedikt
  • 879
  • 4
  • 16
0

If you're using jQuery, the answer is as simple as;

var myCopy = $.extend(true, {}, window.myobj);

If not, this function will create a deep copy the object - including functions and nested objects;

function clone(original) {

    if (original == null || typeof(original) !== 'object')
        return original;

    var theClone = original.constructor.call(this);

    for (var property in original) {
        theClone[property] = clone(original[property]);
    }

    return theClone;

}
Björn
  • 28,401
  • 9
  • 64
  • 81
  • @FlashThunder - you'd want to pass in `true` as first parameter to extend, to create a deep copy, depending on your objects. – Björn Sep 17 '13 at 08:59
  • it is simple 2d object... but the problem is that it doesn't seem to work at all, still refers to the same object, as in given example... – Flash Thunder Sep 17 '13 at 09:03