Using jQuery's datastore vs. expando properties

后端 未结 4 1736
我在风中等你
我在风中等你 2021-01-31 20:22

I\'m developing code using jQuery and need to store data associated with certain DOM elements. There are a bunch of other questions about how to store arbitrary data w

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 20:54

    Using $.data will protect you from memory leaks.

    In IE, when you assign a javascript object to an expando property on a DOM element, cycles that cross that link are not garbage collected. If your javascript object holds a reference to the dom object, the whole cycle will leak. It's entirely possible to end up with hidden references to DOM objects, due to closures, so you may leak without realizing it.

    The jQuery datastore is set up to prevent these cycles from forming. If you use it, you will not leak memory in this way. Your example will not leak because you are putting primitives (strings) on the DOM element. But if you put a more complex object there, you risk leaking.

    Use $.data so you won't have to worry.

提交回复
热议问题