In jQuery 's official documentation, users are reminded that this is a low-level method and should be replaced by the .data() method. $.data(element, key, value) can attach any type of data to DOM elements, but memory leaks caused by circular references should be avoided. The original text is as follows:
The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks. We can set several distinct values for a single element and retrieve them later:
But the problems with this method don't stop there. In JQUERY FORUM, this problem was discussed in depth, and robert.katic proposed a solution. If the $.data() method is applied to the host object, the operation will be optimized, but if this method is used on the local object, the result may not be satisfactory. Under normal circumstances, an element can be deleted using the .remove() method and its respective data cleared. But for local objects, this cannot be completely deleted. These related data continue until the window object is closed. These problems also exist in the event object, because event handlers (handlers) are also stored using this method.
So, the easiest way to solve this problem is to store the data in a new attribute of the local object. Right now:
// ...
if (elem.nodeType) {
cache[id] = dataObject;
elem[expando] = id;
} else {
elem[expando] = dataObject;
}
// ...
However, this method is useless once inheritance issues are involved. Try it:
var parent = {};
var childA = Object.create( parent );
var childB = Object.create( parent );
$.data( parent, "foo", "parent value" );
// This may even be intentional
$.data( childA, "foo" )
// => "parent value"
$.data( childB, "foo" )
// => "parent value"
// This may NOT be intentional
$.data( childA, "foo", "childA value" );
$.data( parent, "foo" )
// => "childA value"
$.data( childB, "foo" )
// => "childA value"
At the beginning, the object storing the data does not exist, so an object is created to store the new value, as shown in the figure
Now, we try to modify the same data of object childA.
The object childA does not have this data, so it looks up the prototype chain. The parent object happens to have this data, and its value is immediately overwritten. Therefore, if you get the value of "foo" from the two objects parent and childB, you will get "childA value" instead of "parent value".