javascript - What does a closed-over variable mean? -


this question has answer here:

the example below taken a stackoverflow answer helps identify closure.

for (var = 0; < 10; i++) {     (function f() {         var i2 = i;         settimeout(function g() {             console.log(i2);         }, 1000);     })(); } 

the following explanation given:

for g:

list variables: console free variable. i2 free variable. find parent scope each free variable bound: console bound global scope. i2 bound scope of f. in scope function referenced? scope of settimeout. hence console not closed on g. hence i2 closed on g.

however not able understand bolded part - explain me?

the term "closed-over" variable in post means variable not accessible caller of function; neither seen nor modifiable context function being called. let's modify code slightly:

var mysettimeout = function (func, timeout) {     console.log = function (arg) { alert(arg); };     = "foobar";     i2 = "barfoo";     settimeout(func, timeout); };  var = "peekaboo";  (function f() {     var i2 = i;     mysettimeout(function g() {         console.log(i2);     }, 1000); })(); 

instead of settimeout, function f calls mysettimeout tries change both value being logged after timeout elapses, , logging function.

after function f has been called , has returned, only function g can see , modify variable i2. console not closed over, because value in global scope; if execute console.log = function (i) { alert(i); };, alert box when timeout fires. however, cannot read or modify i2 in mytimeout - function not see same variable @ all.


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -