这个
cache
您在文档中看到的选项是指浏览器的缓存。
您可以实现
自我记忆
函数在许多方面,其目标是确定参数的函数结果(
id
在您的情况下)只计算一次。
由于您使用的是Ajax请求,我建议您也使用回调参数,例如:
var getInfo = (function () {
var cache = {}; // results will be cached in this object
return function (id, callback) {
if (cache[id] != null) { // if exist on cache
callback(cache[id]);
return;
}
// doesn't exists on cache, make Ajax request and cache it
$.post("info.url", { "id": id }, function (data) {
cache[id] = data; // store the returned data
callback(data);
});
};
})();
示例用法:
getInfo(5, function (data) {
alert(data);
});