Creating a local reference to a jQuery.data key

2020-04-10 16:56发布

问题:

I'm doing some testing on jQuery.data(), and I'm trying to create a local reference to a certain data-key, which I hopefully can change locally and still affect "outside". I think it would be better with an example, due to the semi-long code I posted it on jsFiddle instead of here:

http://jsfiddle.net/esbenp/p4kt2/22/

the output I hope for is:

{1: {length: 1}, total: 1}

but only the length property is affected by incrementing the local variable:

{1: {length: 1}, total: 0}

what should I do?

回答1:

If you store an object (or array) in .data() then you're actually storing a reference to it, so if you do:

var obj = { key: 'value' }
$(el).data('obj') = obj;
obj.key = 'new value';

$(el).data('obj').key will also be new value, because it's the same object.

However if the value stored is a plain type instead (e.g. a number or a string) that a copy of it will be stored:

var n = 5;
$(el).data('obj') = n;
n++;

$(el).data('obj') will still be 5.



回答2:

I am not going to lie - that code is incredibly confusing. Is there a reason why you need to use all those self-executing functions? It seems (at least to this layperson) that you could code this in a much more straightforward way to achieve your goal.

Anyway I am not sure this is the answer you're looking for, but I just stopped the debugger inside AddError so I could understand its scope and what was available. So all you need to do to make it return the output you want is this:

http://jsfiddle.net/qN7wF/2/

functions = {
    AddError: function() {
        console.log(total);
        $(container).data('errors').total++;
        errors.length++;
  },

But given the context... I'm guessing there must be more at play.