Search code examples
jquerypass-by-referencejquery-data

how to disable jquery data function return value by ref?


somehow getting jquery data() function return an object by ref.

it is a way in javascript to point to the object him self without to modify the ref object ?

here is my demonstration of the problem :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var  c= console.log ;
$(document).ready(function(e) {
    var _data   = $("#elem").data();
    var _xdata = _data ; // should be a miror object 
    console.log($("#elem").data() );
    _xdata.id = "changes applied back to #elem.data object !!!"  ;
    console.log($("#elem").data() );
    //any way to separate between $("#elem").data() and _xdata ??
}) ;
</script>
<div id="elem" data-id="1" data-foo="some data"></div> 

Solution

  • This isn't a jQuery issue - its a javascript one. When you're assigning _xdata to _data, you're actually assigning the value of the reference to the _data object (a touch confusing I know). If you'd like to create a "mirror object", you should clone it like:

    var _xdata = jQuery.extend(true, {}, _data);
    

    EDIT: I'm always too slow here, but if you're looking for a shallow copy you could go with:

    var _xdata = jQuery.extend({}, _data);