多个错误,同时在另一个函数内部调用函数 [英] multiple errors while momoizing function inside another function

查看:158
本文介绍了多个错误,同时在另一个函数内部调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西:

function main() {
  function create_node() {
    console.log("create_node")
      (function() {
        var memo;
        console.log(memo);

        function f() {
          var value;
          console.log(value);

          if (memo) {
            value = memo.cloneNode();
            console.log("clone node");
            console.log(value);
          } else {
            var value = document.createElement("div");
            var style = "";
            value.setAttribute("style", style);
            value.innerHTML = "hello";
            console.log("new node");
            console.log(value);
          }
          return value;
        }
        return f;
      })();
  }
  var colection = [];
  for (var i = 0; i < 10; i++) {
    colection.push(create_node());
  };
}
main();

错误(至少在firefox中),而尝试记录create_node。另外,如果我不返回f(),而不是f,它不会被执行。在任何情况下,备忘录总是未定义的。所以我在这里有这三个问题。我想他们来自对复杂闭包缺乏理解,所以我需要一个Javascript rockstar来启发我!

the problem is I get an error (in firefox at least) while try to log "create_node". Also, if I don't return f(), instead of f, it doesn't get executed. In any case, memo is always undefined. So I have this three problems here. I guess they come from a lack of understanding on complex closures, so I'd need a Javascript rockstar to enlighten me!

推荐答案

我发现自己的问题的答案:

I found the answer to my own question:

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");
            memo = value;
        }
        console.log("new node");
        console.log("value: "+value);
        return value;
    }
    return f;
})();

这篇关于多个错误,同时在另一个函数内部调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆