javascript - What does a closed-over variable mean? -
this question has answer here:
- how javascript closures work? 89 answers
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
Post a Comment