8

When I store an object like {a: 1, b: 2 } in jQuery's data, does it copy the object or save a reference to it?

I have a huge object and I want different elements to store different references from different points to the same object, and I don't want it to get copied.

Like

var obj = { 
    a: {
        one: 1, two: 2
    },
    b: {
        apple: 'yummy', banana: 'ehh'
    }
    c: {
        d: {
            'jQuery': jQuery
        }
        e: ['You get the point']
    }
};

$('div').data('info', obj.b);
$('#JQ').data('jq_reference', obj.c.d.jQuery);

3 Answers 3

5

According to my jsfiddle test, it stores a reference.

If I do this:

$('div').data('info', obj.b);
obj.b.apple = 'bleuch';
alert($('div').data('info').apple);

It alerts "bleuch", showing that a reference to the original object is being stored.

Sign up to request clarification or add additional context in comments.

Comments

2

It will save a reference to it.

Javascript objects are never copied, unless you explicitly make a copy.

3 Comments

I think the point of his question was to ask whether jQuery makes such an explicit copy
jQuery never copies things unless you tell it to.
sure, but where's that documented?
0

From http://api.jquery.com/data/

"The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.