javascript - Must memoized functions be defined as variables? -


i've asked question (multiple errors while momoizing function inside function) , i've got nice answer... but! understand little more javascript, i'd know if momoized function can written in style:

function main () {     function memoized_f(){         //memoizing code     } } 

edit: please notice i'm not asking difference in code above, i'm asking if possible memoize second one!

so, how rewrite this?

function main() {   var create_node = (function() {     var memo;     console.log("memo: " + memo);     console.log("create_node")      function f() {       var value;       if (memo) {         value = memo.clonenode();         console.log("clone node");         console.log(value);       } else {         var value = document.createelement("div");         value.innerhtml = "hello";         console.log("new node");         console.log("value: " + value);         memo = value;       }       return value;     }     return f;   })();   var collection = [];   (var = 0; < 10; i++) {     collection.push(create_node());   };   // display results   (var = 0; < 10; i++) {     console.log(i + ". " + collection[i]);   } } main(); 

since functions in javascript object, can use function memoize value. think make more sense in fib example, here original post.

function main() {    // memoizing function    function create_node() {      var value;      // read memo on function object      if (create_node.memo) {        value = create_node.memo.clonenode();        value.innerhtml = 'cloned';        console.log("clone node");        console.log(value);      } else {        var value = document.createelement("div");        value.innerhtml = "hello";        console.log("new node");        console.log("value: " + value);        // retain memo on function object        create_node.memo = value;      }      return value;    }      var collection = [];    (var = 0; < 10; i++) {      collection.push(create_node());    };    // display results    (var = 0; < 10; i++) {      console.log(i + ". " + collection[i]);      document.getelementbyid('container').appendchild(collection[i]);    }  }    main();
<div id="container"></div>


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -