javascript - multiple errors while momoizing function inside another function -
i have this:
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 = []; (var = 0; < 10; i++) { colection.push(create_node()); }; } main();
the problem error (in firefox @ least) while try log "create_node". also, if don't return f(), instead of f, doesn't executed. in case, memo undefined. have 3 problems here. guess come lack of understanding on complex closures, i'd need javascript rockstar enlighten me!
as can't comment, have post reply.
i have seen multiple issues in code:
- the
create_node
function doesn't have return. so, collection empty. - you defining 2 vars in
f
function name "value". second var value might bug. - the var
memo
never assigned. - while returning
f
inside anonymous function, not executing it.
i guessing trying that:
function main() { var memo; function create_node() { console.log("create_node"); memo = (function() { console.log("memo:" + memo); function f() { var value; console.log("value:" + value); if (memo) { value = memo.clonenode(); console.log("clone node" + value); } else { value = document.createelement("div"); var style = ""; value.setattribute("style", style); value.innerhtml = "hello"; console.log("new node:" + value.innerhtml); } return value; } return f; })()(); return memo } var collection = []; (var = 0; < 10; i++) { collection.push(create_node()); }; // display results for(var = 0; i<10;i++) { console.log(i + ". " + collection[i]); } }
Comments
Post a Comment