【问题标题】:Can JavaScript memoization only be used to cache returned results?JavaScript memoization 只能用于缓存返回的结果吗?
【发布时间】:2013-08-02 09:36:50
【问题描述】:

我创建了下面的函数,它将在我网站的每个页面上运行。它运行得足够快,但由于它在每一页上都运行,它似乎是一个很好的缓存候选者,可能使用 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;
  }

 });

【问题讨论】:

    标签: javascript memoization


    【解决方案1】:

    使用frag 作为您的备忘录:

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

    然后更新作业:

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

    参考文献

    【讨论】:

    • 非常感谢!我最近一直在阅读有效的 JavaScript,这一切都很有意义。
    • 没问题。分享知识。
    猜你喜欢
    • 2015-05-09
    • 2012-09-07
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多