1. 程式人生 > >js用閉包實現快取原理

js用閉包實現快取原理

<!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>