开发者

jquery .data() method

开发者 https://www.devze.com 2023-02-27 02:51 出处:网络
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?

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
        }开发者_Python百科
        e: ['You get the point']
    }
};

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


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.


It will save a reference to it.

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


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)."

0

精彩评论

暂无评论...
验证码 换一张
取 消