1.单独在一个页面中使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="js/jquery.js"></script>
<div id="id" class="id">缓存测试</div>
<script>
function getValue(id) {
document.writeln('为:' + id + '创建值');
document.writeln('<br>')
document.writeln('<br>')
return "value is "+ id;
}
var CacheSearchBox = (function () {
var cache = {}, count = [];
return {
search: function (searchId) {
if(searchId in cache) {
document.writeln('从缓存中取数据');
document.writeln('<br>')
return cache[searchId];
}
document.writeln('缓存中无此数据');
document.writeln('<br>')
var value = getValue(searchId);
cache[searchId] = value;
count.push(searchId)
if(count.length > 2) {
document.writeln('缓存量超过最大值,删除最后一个元素');
document.writeln('<br>')
delete cache[count.shift()];
}
document.writeln('当前缓存对象内容:' + JSON.stringify(cache));
document.writeln('<br>')
document.writeln('当前缓存数组内容:' + JSON.stringify(count));
document.writeln('<br>')
},
clear: function (searchId) {
if(searchId in cache) {
delete cache[searchId];
count.splice(count.indexOf(9), 1)
document.writeln('清除缓存对象:' + searchId);
document.writeln('<br>')
document.writeln('当前缓存对象内容:' + JSON.stringify(cache));
document.writeln('<br>')
}
}
};
})();
CacheSearchBox.search('1');
CacheSearchBox.search('1');
CacheSearchBox.search('2');
CacheSearchBox.search('2');
CacheSearchBox.search('3');
CacheSearchBox.clear('3')
</script>
</body>
</html>
2.将闭包放到一个单独js文件中使用
2.1.创建 cache.js 文件
;(function (window) {
function getValue(id) {
document.writeln('为:' + id + '创建值');
document.writeln('<br>')
document.writeln('<br>')
return "value is "+ id;
}
var CacheSearchBox = (function () {
var cache = {}, count = [];
return {
search: function (searchId) {
if(searchId in cache) {
document.writeln('从缓存中取数据');
document.writeln('<br>')
return cache[searchId];
}
document.writeln('缓存中无此数据');
document.writeln('<br>')
var value = getValue(searchId);
cache[searchId] = value;
count.push(searchId)
if(count.length > 2) {
document.writeln('缓存量超过最大值,删除最后一个元素');
document.writeln('<br>')
delete cache[count.shift()];
}
document.writeln('当前缓存对象内容:' + JSON.stringify(cache));
document.writeln('<br>')
document.writeln('当前缓存数组内容:' + JSON.stringify(count));
document.writeln('<br>')
},
clear: function (searchId) {
if(searchId in cache) {
delete cache[searchId];
count.splice(count.indexOf(9), 1)
document.writeln('清除缓存对象:' + searchId);
document.writeln('<br>')
document.writeln('当前缓存对象内容:' + JSON.stringify(cache));
document.writeln('<br>')
}
}
};
})();
window.CacheSearchBox = CacheSearchBox;
})(window);
2.2.在需要的地方引用 cache.js 文件并使用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="js/jquery.js"></script>
<script src="js/cache.js"></script>
<div id="id" class="id">缓存测试</div>
<script>
CacheSearchBox.search('1');
CacheSearchBox.search('1');
CacheSearchBox.search('2');
CacheSearchBox.search('2');
CacheSearchBox.search('3');
CacheSearchBox.clear('3')
</script>
</body>
</html>