Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain me this javascript object "copy" behavior

I have the following code (I am using the jQquery libary):

var obj = {};
var objstring = '{"one":"one","two":"two","three":"three"}'

// first console output
console.log(objstring);

var jsonobj = $.parseJSON(objstring);

// second console output
console.log(jsonobj);

obj.key = jsonobj;
obj.key.test = "why does this affect jsonobj? (even in the second console output)";

// third console output
console.log(jsonobj);

My Question: When I do obj.key = jsonobj and I change values in the new obj.key. Why do values in jsonobj then also change? And how would I avoid that? (I want a new "copy" of jsonobj).

I made this test case: http://jsfiddle.net/WSgVz/

like image 916
Hans Avatar asked Jul 06 '11 19:07

Hans


1 Answers

I want to address a small piece of what is going on here, since others have done so well addressing the larger issues of JavaScript object references:

// second console output
console.log(jsonobj);

obj.key = jsonobj;
obj.key.test = "why does this affect jsonobj? (even in the second console output)";

This is the result of a documented WebKit bug, that console.log statements do not output the object at the time of calling console.log, but instead some time later.

like image 142
Domenic Avatar answered Sep 25 '22 06:09

Domenic