zoukankan      html  css  js  c++  java
  • jQuery在去除缓存数据的一个失误

    如果独自放着jQuery做事,它绝对做得很好,但jQuery充许与其他库共存在,有些事就防不胜防了。看下面代码,

    data :function (elem, name,data){
        //略
    },
    removeData: function (elem, name) {
        elem = elem == window ? windowData : elem;
    
        var id = elem[expando];
    
        // If we want to remove a specific section of the element's data
        if (name) {
            if (jQuery.cache[id]) {
        //★★★★★★★
                // Remove the section of cache data
                delete jQuery.cache[id][name];
    
                // If we've removed all the data, remove the element's cache
                name = "";
    
                for (name in jQuery.cache[id])
                break;
    
                if (!name) jQuery.removeData(elem);
        //★★★★★★★
            }
    
            // Otherwise, we want to remove all of the element's data
        } else {
            // Clean up the element expando
            try {
                delete elem[expando];
            } catch(e) {
                // IE has trouble directly removing the expando
                // but it's ok with using removeAttribute
                if (elem.removeAttribute) elem.removeAttribute(expando);
            }
    
            // Completely remove the data cache
            delete jQuery.cache[id];
        }
    },
    

    留意星号包围的区域,John Resig的想法是,如果把元素节点的对应的缓存体的键值对全部移除后,就把此缓存体从cache中去掉。举个通俗的例子,cache就是一家银行,页面上的元素节点(elem)就是一个个人,每个人可以通过data方法在银行里开个帐户(id),而存折就是elem的那个expando属性,这个帐户可以做存许多东西,每样东西都分开管理的,如果帐户里面的东西都取光就会自动注销这个帐户。嗯,本来就应该这样,没用的东西就应该收CG回收掉,节省内存。

    下面是一个仿制品

    但如果jQuery与一些在Object原型进行了扩展的库共库呢?假设在它里面添加了个aa属性……

    这时就无法清除缓存体了,遇到这篇文章提到的问题《Google Closure: 糟糕的JavaScript》,真是百密一疏!这也很好的教训了我们不要对Object.prototype这个最基本的东西做扩展,Prototype最近的版本也对此做了修正。那么如何排除干扰呢?

  • 相关阅读:
    JS----事件
    JS----计时器
    JS----文档对象模型
    JS----基本数据类型
    JS----函数
    JS----数组
    JS----正则表达式
    CSS----盒子模型与浮动
    Web-9月13日随笔
    Web-9月14日随笔
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/1623626.html
Copyright © 2011-2022 走看看