JavaScript memoization只能用于缓存返回的结果吗?

时间:2013-08-02 09:36:51

标签: javascript memoization

我已经创建了以下功能,该功能将在我网站的每个页面上运行。它运行得足够快,但是当它在每个页面上运行时,它似乎是一个很好的候选者,可以使用memoization进行缓存。在我对这个主题的研究中,memoization总是缓存用return语句发出的结果。这是完全合理的,但由于我的功能没有返回任何东西,我想知道它是否仍然可以缓存?使用除了记忆之外的其他东西?

这是我的功能:

// A requirejs module
define(function() {

 var loadMenu,
   cssdisabled,
   testcss,
   currstyle; 

 /*  
  *  Dynamically create a form that looks like this:
  *
  *  <form action="/search.html" id="js-searchbox" class="form">
  *    <input type="text" name="q" id="tipue_search_input"
  *     placeholder="Search...">
  *    <input type="submit" id="tipue_search_button" value="Search">
  *  </form>
  */
 loadMenu = function() {
   var loadBox = document.getElementById("searchbox"),
     footerBox = document.getElementById("search-about-column"),
     frag = document.createDocumentFragment(),
     form = document.createElement("form"),
     searchTextBox = document.createElement("input"),
     searchButton = document.createElement("input");

 // set attributes for form
 form.action = "/search.html";
 form.setAttribute("role", "search");
 form.id = "js-searchbox";
 form.setAttribute("class", "form");

 // set attributes for Search text box
 searchTextBox.type = "text";
 searchTextBox.name = "q";
 searchTextBox.id = "tipue_search_input";
 searchTextBox.placeholder = "Search...";

 // set attributes for Submit button
 searchButton.type = "submit";
 searchButton.setAttribute("class", "btnSearch");
 searchButton.value = "Search";

 // Arrange elements
 form.appendChild(searchTextBox);
 form.appendChild(searchButton);

 // Load arranged elements into document fragment
 frag.appendChild(form);

 // Load document fragment into #searchbox, which is already on the page
 loadBox.appendChild(frag);
}

 cssdisabled = false;

 testcss = document.createElement('div');

 testcss.style.position = 'absolute';

 document.getElementsByTagName('body')[0].appendChild(testcss);

 if (testcss.currentStyle) {
   currstyle = testcss.currentStyle['position'];
 }

 else if (window.getComputedStyle) {
  currstyle = document.defaultView.getComputedStyle(testcss, null).getPropertyValue('position');
} 

 cssdisabled = (currstyle === 'static') ? true : false;

 document.getElementsByTagName('body')[0].removeChild(testcss);

 if (cssdisabled === false) {
   loadMenu();
 } else {
   return false;
  }

 });

1 个答案:

答案 0 :(得分:0)

使用frag作为备忘录:

frag.appendChild(form);
loadMenu.frag = frag;

然后更新作业:

loadMenu = loadMenu.frag || function() {...}

<强>参考