jQuery对象数据缓存Cache原理及jQuery.data方法区别介绍

2020-05-22 22:01:21易采站长站整理

return;
}
var privateCache, thisCache, ret,
//jQuery.expando这是一个唯一的字符串,是这介jquery对象产生的时候就生成了。
internalKey = jQuery.expando,
getByName = typeof name === “string”,
// 必须区分处理DOM元素和JS对象,因为IE6-7不能垃圾回收对象跨DOM对象和JS对象进行的引用属性
isNode = elem.nodeType,
// 如果是DOM元素,则使用全局的jQuery.cache
// 如果是JS对象,则直接附加到对象上
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === “events”;
// 避免做更多的不必要工作,当尝试在一个没有任何数据的对象上获取数据时
// 对象没有任何数据,直接返回
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
// id不存在的话就生成一个
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
// 如果是DOM元素则在元素上产生唯一的ID 并且以jQuery.expando
//为属性值为id保存在elem元素上,以便以后再根据jQuery.expando来查找ID。
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
// JS对象则直接使用jQuery.expando,既然是直接附加到对象上,又何必要id呢?
// 避免与其他属性冲突!
id = internalKey;
}
}
//// 当我们试着访问一个键是否含有值的时候,如果不存在jQuery.cache[id]值,
// 初始化jQuery.cache[id]值 为一个空对象{}
if ( !cache[ id ] ) {
cache[ id ] = {};
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
// data是接收对象和函数,浅拷贝
if ( typeof name === “object” || typeof name === “function” ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
/ 存储对象,存放了所有数据的映射对象
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object’s internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
// jQuery内部数据存在一个独立的对象(thisCache.data==thisCache[ internalKey ])
//上,为了避免内部数据和用户定义数据冲突
if ( !pvt ) {
// 存放私有数据的对象不存在,则创建一个{}
if ( !thisCache.data ) {
thisCache.data = {};
}
// 使用私有数据对象替换thisCache