js用闭包实现缓存原理

    xiaoxiao2021-03-25  100

    <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <title>Title</title> </head> <body> </body> <script>     //缓存:一般来说对于一些经常使用的数据,并且这些数据都是从后端获取过来的来进行缓存     //用户id:用户的唯一标识     //登录(/user/login)--->获取id     //修改用户信息:--->必须要知道用户的id才能该用户的信息     //购物车/收藏夹--->必须要知道用户的id才能该用户的信息     //对于一些经常使用,但是经常修改的数据就不能保存了,比如说搜索结果     //外层函数只执行了一次,只产生了唯一的执行环境,也就只产生了唯一的cacheObj对象,用户想要操作这个对象,必须通过我们暴露的4个闭包函数     var CacheManager=(function(){         var cacheObj={};         return {             setItem:function(key,value){                 cacheObj[key]=value;             },             getItem:function(key){                 return cacheObj[key];             },             removeItem:function(key){                 delete cacheObj[key];             },             //清空缓存             clear:function(){                 cacheObj={};             }         }     })();     CacheManager.setItem("name","lisi");     alert(CacheManager.getItem("name"));     CacheManager.setItem("age","20");     CacheManager.setItem("gender","女");     CacheManager.setItem("userId","888");     CacheManager.removeItem("age");     alert(CacheManager.getItem("gender"));//"女"     alert(CacheManager.getItem("age"));//undefined </script> </html>
    转载请注明原文地址: https://ju.6miu.com/read-8025.html

    最新回复(0)