javascript - JS why is other code ignored and only return executed -
i got code gave same result:
var number = 0; function a(){ number++; //outside return function return function(){ return number; }; } var b = a(); //outside loop for(i=0;i<10;i++){ console.log("loop: "+(i+1)+" :"+b()); }
i found solution (1):
var number = 0; function a(){ number++; //outside return function return function(){ return number; }; } for(i=0;i<10;i++){ var b = a(); //inside loop console.log("loop: "+(i+1)+" :"+b()); }
and apparently should've gotten "correct" solution (2):
var number = 0; function a(){ return function(){ number++; //inside return function return number; }; } var b = a(); //outside loop for(i=0;i<10;i++){ console.log("loop: "+(i+1)+" :"+b()); }
in solution 1: thought putting var b in for-loop, "refresh" var number every loop, , did because every loop 1 added.
in solution 2: don't see why number++ should added return function looped. i.m.o. whole a() function run through in original question , not code in return method? not, why?
in first version a()
called once, number++
called once. in second version call a()
every iteration number++
called on every iteration. in first version b
same function , in second new 1 every time call a()
.
Comments
Post a Comment