Javascript Object Inconsistency
Consider an object called obj
that I believe to be equal to {x: 1, y: 'hi'}
(It was defined a while ago, and has undergone some modifications through various functions thr开发者_JAVA技巧oughout its lifetime).
console.log(obj);
console.log(obj.y);
console.log(obj.x);
The result of this in both Chrome and FF3.6 shows the result of console.log(obj)
as
obj = {x: 1, y: 'hi'}
as expected. The result of obj.y
prints hi
as expected, but the result of obj.x
prints 0
.
I do not understand how this inconsistency can happen. It prints correctly as the object as a whole, but then on the very next line prints a different value upon accessing the parameter directly.
I assume this has something to do with shared object structure, because I define obj
and store it in an array arr
. Then I put obj
on a DOM element using jQuery's .data()
function. I later retrieve the object using .data()
from the DOM element and modify the object some more (parameter x
specifically). The oddities I am seeing are happening when I later go access the object from arr
.
Mostly, I just want to understand why the console.log shows an inconsistency
When you fetch an object from ".data()", you do not get a copy of the object - you get the object itself. There's only one. Thus, if you do this:
$('#foo').data('obj', { x: 1, y: "hi" });
and then:
var obj = $('#foo').data('obj');
// ...
if (whatever) obj.x = 0;
then later when you reference "obj" via ".data()" again, the "x" property will be zero (if the "if" condition had been true, in this case).
You can avoid this by making a copy of the data yourself, if what you want is a copy of course.
精彩评论